我需要编写一个函数,该函数使用正文中的string参数创建列的名称。例如,
dt1 <- data.table( Col_1999_L = c(6,7,8,9,10),
Col_1999_R = c(1,-2,3,-4,5),
Col_2001_L = c(-8-3,5, 2,-1),
Col_2001_R = c(-1,2,-3,4,5)
)
在这里,1999、2001确实代表了几年。我的输出应该像在dt2中一样,在这里我创建了检查某些条件的新列。
dt2 <- dt1 %>%
select(c("Col_1999_L", "Col_1999_R")) %>%
mutate(
New1 = if_else(Col_1999_L >= 0, "pos", "neg"),
New2 = case_when(
Col_1999_L >=0 & Col_1999_R >=0 ~ "pos",
Col_1999_L >=0 & Col_1999_R < 0 ~ "neg",
))
dt2
实际上,我需要编写一个每年为df2之类的表的函数。
我尝试过这样的事情(这是错误的):
my_function <- function(dt, Year) {
dt %>%
mutate(
New1 = if_else(Col_"Jahr"_L >= 0, "pos", "neg"),
New2 = case_when(
Col_"Year"_L >=0 & Col_"Year"_R >=0 ~ "pos",
Col_"Year"_L >=0 & Col_"Year"_R < 0 ~ "neg"))
}
my_function(dt1, 1999)
如何正确编写任何帮助?谢谢
我们可以paste
将值转换为sym
bol,然后求值(!!
)。如果创建了字符串,则tidyverse首选方法是将其转换为sym
bol,然后求值。
library(dplyr)
my_function <- function(dt, Year) {
nm1 <- rlang::sym(paste0("Col_", Year, "_R"))
nm2 <- rlang::sym(paste0("Col_", Year, "_L"))
dt %>%
mutate(
New1 = if_else(!! nm2 >= 0, "pos", "neg"),
New2 = case_when(
!!nm2 >=0 & !!nm1 >=0 ~ "pos",
!!nm2 >=0 & !!nm1 < 0 ~ "neg"))
}
my_function(dt1, 1999)
# Col_1999_L Col_1999_R Col_2001_L Col_2001_R New1 New2
#1: 6 1 -8 -1 pos pos
#2: 7 -2 -3 2 pos neg
#3: 8 3 5 -3 pos pos
#4: 9 -4 2 4 pos neg
#5: 10 5 -1 5 pos pos
或者,如果我们传递完整的未加引号的列名,则可以使用curly-curly
运算符({{}}
)
my_function <- function(dt, colnm1, colnm2) {
dt %>%
mutate(New1 = if_else({{colnm2}} > 0, "pos", "neg"),
New2 = case_when({{colnm2}} >= 0 & {{colnm1}} >=0 ~ "pos",
{{colnm2}} >= 0 & {{colnm1}} < 0 ~ "neg"))
}
my_function(dt1, Col_1999_R, Col_1999_L)
# Col_1999_L Col_1999_R Col_2001_L Col_2001_R New1 New2
#1: 6 1 -8 -1 pos pos
#2: 7 -2 -3 2 pos neg
#3: 8 3 5 -3 pos pos
#4: 9 -4 2 4 pos neg
#5: 10 5 -1 5 pos pos
dt1 <- data.table( Col_1999_L = c(6,7,8,9,10),
Col_1999_R = c(1,-2,3,-4,5),
Col_2001_L = c(-8, -3,5, 2,-1),
Col_2001_R = c(-1,2,-3,4,5)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句