从R中具有不同值的现有列创建一个新列

时间:2018-07-05 14:40:10

标签: r if-statement

我有一个数据框,其中包含六月,五月,七月的各个值。我正在尝试为每个月使用新值创建新列。如果该值大于或等于100,我希望将其更改为100,并在小于100时保留该值。这是df:

June <- c(100,50,200)
May <- c(250, 100, 20)
July <- c(20, 300, 20)

df <- data.frame(June, May, July)

我的目标是使df像这样:

June <- c(100,50,200)
May <- c(250, 100, 20)
July <- c(20, 300, 20)
June_new <- c(100,50,100)
May_new <- c(100,100,20)
July_new <- c(20,100,20)

df2 <- data.frame(June, May, July,June_new, May_new, July_new)

谢谢

1 个答案:

答案 0 :(得分:2)

使用简单的ifelse检查条件并将其添加到df本身中,怎么样?

df$new_June <- ifelse(df$June>=100, 100, df$June)
df$new_May <- ifelse(df$May>=100, 100, df$May)
df$new_July <- ifelse(df$July>=100, 100, df$July)

df值之前:

> df
  June May July
1  100 250   20
2   50 100  300
3  200  20   20

运行命令后的df值:

df$new_June <- ifelse(df$June>=100, 100, df$June)
df$new_May <- ifelse(df$May>=100, 100, df$May)
df$new_July <- ifelse(df$July>=100, 100, df$July)
df

  June May July new_June new_May new_July
1  100 250   20      100     100       20
2   50 100  300       50     100      100
3  200  20   20      100      20       20
>