我是R的新手,我已经创建了一些功能,但我有点迷失在这里:我需要提出“结果”列的值。我目前有一个数据框,其列名为“Seasons”和“Total”。但是,我需要添加另一列“结果”。为此,我需要从另一个数据框中查找“乘数”值。
Seasons Total Result
Winter 200 100
Fall 50 25
Spring 10 5
Summer 120 12
我有其他数据框,其列和行值为
Multiplier Value
Win1 0.5
Win2 0.1
当季节为冬季,秋季和春季时,Win1应仅乘以“总计”,而当季节为夏季时,Win2必须仅乘以“总计”。这应该是“结果”列的值。
谢谢
答案 0 :(得分:0)
使用dplyr
的另一个选项可以是;
df1 %>% mutate(Result = ifelse(Seasons %in% c("Winter", "Fall", "Spring"),
Total*df2[df2$Multiplier=="Win1",]$Value,
Total*df2[df2$Multiplier=="Win2",]$Value))
# Seasons Total Result
#1 Winter 200 100
#2 Fall 50 25
#3 Spring 10 5
#4 Summer 120 12
# OR 2nd Option is using with
df1$Result <- with(df1, ifelse(Seasons %in% c("Winter", "Fall", "Spring"),
Total*df2[df2$Multiplier=="Win1",]$Value,
Total*df2[df2$Multiplier=="Win2",]$Value) )
数据强>
df1 <- read.table(text = "Seasons Total
Winter 200
Fall 50
Spring 10
Summer 120", header = T, stringsAsFactor =F)
df2 <- read.table(text = "Multiplier Value
Win1 0.5
Win2 0.1", header = T, stringsAsFactor = F)
答案 1 :(得分:0)
您可以使用ifelse()
df$Result <- ifelse(df$Seasons=="Summer", df2$Value[2]*df$Total, df2$Value[1]*df$Total)