summing rows of specific columns then dividing by the sum
Try this way to specify the column (by sub-setting Df
), and then indicating the margin as 1
Df_new = t(apply(Df[,c(1:3)], 1, \(x) x/sum(x)))
lose draw win
[1,] 0.5000 0.1428571 0.3571429
[2,] 0.0625 0.1250000 0.8125000
sum cells of certain columns for each row
You could do something like this:
summed <- rowSums(zscore[, c(1, 2, 3, 5)])
SUM specific column values that have integers where row meets a condition and place in new row
you can use rolling window to calculate the sum of pair of two columns, then concat the result
col=[1,0,1,0]
df2=pd.concat([df,
df.loc[df['ID'].isin(['AA','BB']) ]
.rolling(2, axis=1).sum() # calc rolling windows sum of two columns
.shift(-1, axis=1) # shift result to left
.fillna(0) # fill null values
.mul(col) # multipley to keep sum in alternate columns
]
)
df2.sort_index(axis=0, inplace=True)
#create a column with a new ID
df2['ID2']=df2['ID']+'_New'
# fill NA values with the row above
df2['ID2'].fillna(method='ffill', inplace=True)
#reset index
df2=df2.reset_index()
# where the ID is null (our new summed row), assign the ID2 to ID
df2.loc[df2['ID'].isna(), 'ID'] = df2['ID2']
#drop unwanted columns
df2.drop(columns=['ID2', 'index'], inplace=True)
df2
ID Q121 Q221 Q321 Q421
0 AA 8.0 4.8 3.1 5.3
1 AA_New 12.8 0.0 8.4 0.0
2 BB 0.6 0.7 0.3 0.9
3 BB_New 1.3 0.0 1.2 0.0```
Related Topics
How to Find the Package Name in R for a Specific Function
R - Replace Specific Value Contents with Na
Row Not Consolidating Duplicates in R When Using Multiple Months in Date Filter
Factor with Comma and Percentage to Numeric
Regression with Heteroskedasticity Corrected Standard Errors
Dividing Each Cell in a Data Set by the Column Sum in R
Developing Shiny App as a Package and Deploying It to Shiny Server
Clickable Links in Shiny Datatable
Repeat the Re-Sampling Function for 1000 Times? Using Lapply
How to Retrieve the Client's Current Time and Time Zone When Using Shiny
How to Know Which Cluster Do the New Data Belongs to After Finishing Cluster Analysis
Plot Title at Bottom of Plot Using Ggplot2
How to Compare Two Factors with Different Levels
R: Formatting Plotly Hover Text
Convergence Error for Development Version of Lme4
Include Text Control Characters in Plotmath Expressions
Display Duplicate Records in Data.Frame and Omit Single Ones