简体   繁体   中英

creating new columns in R with similar paterns

Imagine I have three variables names 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. 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 :

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 .

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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