嗨,我想通过将数据框中的某些列乘以 R 中的单个列来生成多个新列,并将新列附加到原始 df。
我的初始数据格式如下
ID amount supplier_1 supplier_2 supplier_3 ... supplier_100
1 10 0 1 0 0
1 15 1 0 0 0
1 20 1 0 0 0
2 5 0 0 0 1
2 8 0 1 0 0
2 10 0 0 0 1
#I have more than 100 suppliers in this df.
我想要的输出是将所有 seller_n 列(虚拟变量)乘以金额。
ID amount supplier_1 supplier_2 supplier_3 ... supplier_100
1 10 0 1 0 0
1 15 1 0 0 0
1 20 1 0 0 0
2 5 0 0 0 1
2 8 0 1 0 0
2 10 0 0 0 1
amt*supplier_1 amt*supplier_2 amt*supplier_3 ..... amt*supplier_100 Total_amt
0 10 0 0 45
15 0 0 0 45
20 0 0 0 45
0 0 0 5 23
0 8 0 0 23
0 0 0 10 23
#total_amt is the sum of amount conditional on ID.
我在这里找到了类似的,并尝试了带有 function(col) 命令的 mutate_all 但没有成功
如果有人能提供一些建议,我将不胜感激!
您可以将
dplyr
与 mutate()
和 across()
一起使用,对许多列执行相同的操作。例如
dd %>% mutate(across(starts_with("supplier"), ~amount * .x))
# ID amount supplier_1 supplier_2 supplier_3 supplier_100
# 1 1 10 0 10 0 0
# 2 1 15 15 0 0 0
# 3 1 20 20 0 0 0
# 4 2 5 0 0 0 5
# 5 2 8 0 8 0 0
# 6 2 10 0 0 0 10
要添加总金额,如果您假设只有一个供应商有值且其值为 0/1,则只需按 ID 将金额与
相加即可dd %>%
mutate(across(starts_with("supplier"), ~amount * .x)) %>%
mutate(Total_amt = sum(amount), .by=ID)
使用样本数据进行测试
dd <- read.table(text="
ID amount supplier_1 supplier_2 supplier_3 supplier_100
1 10 0 1 0 0
1 15 1 0 0 0
1 20 1 0 0 0
2 5 0 0 0 1
2 8 0 1 0 0
2 10 0 0 0 1", header=T)
在基础 R 中,您可以使用
lapply
在执行操作时同时创建新列:
ccols <- names(df)[grep("supplier", names(df))]
# [1] "supplier_1" "supplier_2" "supplier_3" "supplier_100"
df[paste0("amt_x_",ccols)] <- lapply(df[ccols], \(x) df$amount * x)
输出:
# ID amount supplier_1 supplier_2 supplier_3 supplier_100 amt_x_supplier_1 amt_x_supplier_2 amt_x_supplier_3 amt_x_supplier_100
# 1 1 10 0 1 0 0 0 10 0 0
# 2 1 15 1 0 0 0 15 0 0 0
# 3 1 20 1 0 0 0 20 0 0 0
# 4 2 5 0 0 0 1 0 0 0 5
# 5 2 8 0 1 0 0 0 8 0 0
# 6 2 10 0 0 0 1 0 0 0 10
数据:
df <- read.table(text = "ID amount supplier_1 supplier_2 supplier_3 supplier_100
1 10 0 1 0 0
1 15 1 0 0 0
1 20 1 0 0 0
2 5 0 0 0 1
2 8 0 1 0 0
2 10 0 0 0 1", h = TRUE)
或者,如果您只想替换所需列中的现有值,只需执行以下操作:
df[ccols] <- lapply(df[ccols], \(x) df$amount * x)
覆盖列