在这样的数据中:
data.frame (com = c("col1","em"), stock1 = c(2.6, 0), aim = c(0,3.10))
如何用com“ em”向行的所有行添加减号
预期结果示例:
data.frame (com = c("col1","em"), stock1 = c(2.6, 0), aim = c(0,-3.10))
com stock1 aim
1 col1 2.6 0.0
2 em 0.0 -3.1
答案 0 :(得分:2)
使用ifelse
:
df1 <- data.frame (com = c("col1","em"), stock1 = c(2.6, 0), aim = c(0,3.10))
df1$aim <- ifelse(df1$com == "em", -df1$aim, df1$aim)
df1
com stock1 aim
1 col1 2.6 0.0
2 em 0.0 -3.1
答案 1 :(得分:1)
这是如何工作的?
xy <- data.frame (com = c("col1","em"), stock1 = c(2.6, 0), aim = c(0,3.10))
find.com <- -which(names(xy) == "com")
xy[xy$com == "em", find.com] <- -xy[xy$com == "em", find.com]
xy
com stock1 aim
1 col1 2.6 0.0
2 em 0.0 -3.1