繁体   English   中英

在 R 中创建具有相似模式的新列

[英]creating new columns in R with similar paterns

想象一下,我有三个变量名称 day_to_A、day_to_B、day_to_C:

df = 
day_to_A day_to_B day_to_C
2        5        2
1        6        3

我想创建名为 Date_to_A、Date_to_B 和 Date_to_C 的列,它们是相同的旧列,但添加了第二个列。 到目前为止,我已经完成了:

df = df %>%
  select(grep(^days_to_)) %>%
  mutate()

结果应如下所示:

df = 
Date_to_A Date_to_B Date_to_C
4        7        4
3        8        5

您可以将rename_withmutate_at结合使用:

df %>% 
mutate_at(vars(starts_with("days_to_")), ~.x+2) %>%
rename_with(~gsub("^days_to_", "Date_to_", .x))

请注意,这不会创建新列,而是更改现有列。

使用grepsetNames

setNames(d[g <- grep("day_to", names(d), value=TRUE)] + 2, gsub("day_to", "Date_to", g))
#   Date_to_A Date_to_B Date_to_C
# 1         4         7         4
# 2         3         8         5

只需将它与cbind一起使用。

res <- cbind(d, 
             setNames(d[g <- grep("day_to", names(d), value=TRUE)] + 2, 
                      gsub("day_to", "Date_to", g)))
res
#   day_to_A day_to_B day_to_C Date_to_A Date_to_B Date_to_C
# 1        2        5        2         4         7         4
# 2        1        6        3         3         8         5

数据:

d <- structure(list(day_to_A = 2:1, day_to_B = 5:6, day_to_C = 2:3), class = "data.frame", row.names = c(NA, 
-2L))
library(dplyr)
library(stringr)
df %>% 
  mutate(across(starts_with("day_to"), ~ . + 2, .names = "date_to_{.col}")) %>%
  rename_with(.fn = ~ str_replace(.x, "date_to_day_to", "date_to"))
#   day_to_A day_to_B day_to_C date_to_A date_to_B date_to_C
# 1        2        5        2         4         7         4
# 2        1        6        3         3         8         5

使用此数据:

df = read.table(text = "
day_to_A day_to_B day_to_C
2        5        2
1        6        3", header = T)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM