[英]creating new columns in R with similar paterns
Imagine I have three variables names day_to_A, day_to_B, day_to_C:想象一下,我有三个变量名称 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
I want to create columns named Date_to_A, Date_to_B, and Date_to_C that are the same old columns but adding the number two.我想创建名为 Date_to_A、Date_to_B 和 Date_to_C 的列,它们是相同的旧列,但添加了第二个列。 So far I have done:
到目前为止,我已经完成了:
df = df %>%
select(grep(^days_to_)) %>%
mutate()
the outcome should look like the following:结果应如下所示:
df =
Date_to_A Date_to_B Date_to_C
4 7 4
3 8 5
You can use rename_with
combined with mutate_at
:您可以将
rename_with
与mutate_at
结合使用:
df %>%
mutate_at(vars(starts_with("days_to_")), ~.x+2) %>%
rename_with(~gsub("^days_to_", "Date_to_", .x))
Note, that this wont create new columns, but change the existing ones.请注意,这不会创建新列,而是更改现有列。
Using grep
and setNames
.使用
grep
和setNames
。
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
Just use it with cbind
.只需将它与
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
Data:数据:
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
Using this data:使用此数据:
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.