I am working with data frame and I need to extract data as follows:
I have the following data frame.
a = c(1:40)
b = c(41:80)
c = c(81:120)
d = c('a','b','c','d','e')
e = NA
f = NA
g = NA
df = cbind.data.frame(a,b,c,d,e,f,g)
names(df) = c('1m','2m','3m','reg','1m_comp','2m_comp','3m_comp')
1m 2m 3m reg 1m_comp 2 m_comp 3m_comp
1 41 81 a NA NA NA
2 42 82 b NA NA NA
3 43 83 c NA NA NA
4 44 84 d NA NA NA
5 45 85 e NA NA NA
6 46 86 a NA NA NA
I use within function to fill the 'comp' columns with the values from the '1m','2m' columns if 'reg' column has a certain value.
I do this:
df = within(df, {
1m[reg=='a'] <- 1m_comp[reg=='a']
2m[reg=='a'] <- 2m_comp[reg=='a']
3m[reg=='a'] <- 3m_comp[reg=='a']})
The dataframe that I am working on has 46+46 such columns(the columns and the comps). Instead of writing 46 lines of code, I tried
df = within(df, {
for (i in 1:46) {
str_c(i,'m_comp')[reg=='a'] = str_c(i,'m')[reg=='a']}})
However, I see no change in my data frame. I don't see any error either.
Edit: Resolved now! Thanks db
If you don't want to have to hard code all of the column names you can use something like this.
comp.cols <- colnames(df)[grepl("_comp", colnames(df)) == TRUE]
non.comp.cols <- sub("_comp", "", comp.cols)
df[df[,"reg"] == "a", comp.cols] <- df[df[,"reg"] == "a", non.comp.cols]
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.