简体   繁体   中英

Creating rowSums of one variable conditional on the value of another variable in R

I'm hoping compute the sum of var1 through var10 using the rowSums function in R, but only for the rows in which var11 is equal to 1.

I've attempted subsetting my data to create a sum of var1-var10 only for data in which var11 is equal to 1 then remerging my original dataframe with the subsetted dataframe. The issue with this is that it leads to my main dataset excluding all rows for all variables in which var11 is equal to 1, when I'd like to retain those rows for the full dataset, but have them specified as NA only for the sum of var1-var10.

First I create a sample data:

m1=matrix(sample(x = 1:10, size = 100, replace = T), nrow=10, ncol=10)
m2= c(sample(1:3, size=10, replace=T))
df = data.frame(cbind(m1, m2))
names(df) = c('var1', 'var2', 'var3', 'var4', 'var5', 'var6', 'var7', 'var8', 'var9', 'var10', 'var11')

which looks like below:

df
# var1 var2 var3 var4 var5 var6 var7 var8 var9 var10 var11
# 1    10    5    1    9    1    6    7    3    8     3     1
# 2    10   10    3    9    4   10    4    3   10     6     1
# 3    10    9    3    6    9    6    1    5   10     1     2
# 4     7    5    2    8   10    9    9    3    3     4     2
# 5     9    8    8   10    1    6    7    7    3     7     2
# 6     5    5    1    1    4    1    6    6    8     2     1
# 7     3    6    9    6    9    1    1    8    6     8     2
# 8     3   10   10    2    2   10    4    7    7     2     2
# 9     4   10    1    9    4    4    2    2    6     8     3
# 10    3   10    2    5    5   10    1    7    6     4     2

Then I'll do the conditioning:

df$ROWSUMS=NA
df[df$var11 == 1, 'ROWSUMS']=rowSums(df[df$var11 == 1,1:10])
df

# var1 var2 var3 var4 var5 var6 var7 var8 var9 var10 var11 ROWSUMS
# 1    10    5    1    9    1    6    7    3    8     3     1      53
# 2    10   10    3    9    4   10    4    3   10     6     1      69
# 3    10    9    3    6    9    6    1    5   10     1     2      NA
# 4     7    5    2    8   10    9    9    3    3     4     2      NA
# 5     9    8    8   10    1    6    7    7    3     7     2      NA
# 6     5    5    1    1    4    1    6    6    8     2     1      39
# 7     3    6    9    6    9    1    1    8    6     8     2      NA
# 8     3   10   10    2    2   10    4    7    7     2     2      NA
# 9     4   10    1    9    4    4    2    2    6     8     3      NA
# 10    3   10    2    5    5   10    1    7    6     4     2      NA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM