检测一行是否等于一,然后插入另一列的值

时间:2019-02-15 18:54:39

标签: r dataframe

具有输入数据:

如果stock1stock2列中有一个取值为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

3 个答案:

答案 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