具有输入数据:
如果stock1
和stock2
列中有一个取值为com_num
列,那么如何检查这些列
dframe <- data.frame(
com = c("col1","em","col1","em"), com_num = c(3.1,2.1,2.1,4.1),
stock1 = c(1,0,1,1), stock2 = c(1,1,0,1)
)
以下是预期结果的示例
dframe_ex <- data.frame(
com = c("col1","em","col1","em"), com_num = c(3.1,2.1,2.1,4.1),
stock1 = c(3.1,0,2.1,4.1), stock2 = c(3.1,2.1,0,4.1)
)
dframe_ex
com com_num stock1 stock2
1 col1 3.1 3.1 3.1
2 em 2.1 0.0 2.1
3 col1 2.1 2.1 0.0
4 em 4.1 4.1 4.1
答案 0 :(得分:3)
另一个base R
选项
dframe[, 3:4] <- dframe[, 3:4] * dframe[, 2]
dframe
# com com_num stock1 stock2
#1 col1 3.1 3.1 3.1
#2 em 2.1 0.0 2.1
#3 col1 2.1 2.1 0.0
#4 em 4.1 4.1 4.1
答案 1 :(得分:2)
我们可以使用dplyr
中的library(dplyr)
dframe %>%
mutate_at(vars(starts_with("stock")), funs(ifelse(. == 1, com_num, .)))
# com com_num stock1 stock2
# 1 col1 3.1 3.1 3.1
# 2 em 2.1 0.0 2.1
# 3 col1 2.1 2.1 0.0
# 4 em 4.1 4.1 4.1
。
dframe %>%
mutate_at(vars(starts_with("stock")), funs(. * com_num))
# com com_num stock1 stock2
# 1 col1 3.1 3.1 3.1
# 2 em 2.1 0.0 2.1
# 3 col1 2.1 2.1 0.0
# 4 em 4.1 4.1 4.1
或
lapply
具有dframe[grepl("^stock", names(dframe))] <- lapply(dframe[grepl("^stock", names(dframe))],
function(x) x * dframe$com_num)
dframe
# com com_num stock1 stock2
# 1 col1 3.1 3.1 3.1
# 2 em 2.1 0.0 2.1
# 3 col1 2.1 2.1 0.0
# 4 em 4.1 4.1 4.1
的基本R解决方案。
soup.select()
答案 2 :(得分:2)
cols = c("stock1", "stock2")
dframe[cols] = lapply(X = cols, FUN = function(nm) dframe[nm]*dframe["com_num"])
dframe
# com com_num stock1 stock2
#1 col1 3.1 3.1 3.1
#2 em 2.1 0.0 2.1
#3 col1 2.1 2.1 0.0
#4 em 4.1 4.1 4.1