Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

r - code a variable with the values of multiple variables


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If all your columns are numeric, you can use rowSums(). Like this:


df1<- data.frame(ID = c("a", "b", "c", "d", "e"),
                  var1 = c(1,0 ,2 ,0 ,0 ),
                  var2 = c(0, 2, 0, 0, 0),
                  var3 = c(0,0,0,2,2),
                  var4 = c(0,0,NA, NA, NA))

df2$var5 <- rowSums(df1[,2:5], na.rm = TRUE)

df2
#   ID var1 var2 var3 var4 var5
# 1  a    1    0    0    0    1
# 2  b    0    2    0    0    2
# 3  c    2    0    0   NA    2
# 4  d    0    0    2   NA    2
# 5  e    0    0    2   NA    2



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...