user4797853
user4797853

Reputation: 71

Looping on only first x column names

I am using the following code

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}

but I only want the 2nd, 3rd, and 4th columns to change. What is the best way to do this?

Upvotes: 0

Views: 29

Answers (1)

bgoldst
bgoldst

Reputation: 35314

You can use lapply() and vectorized list assignment to do this:

df[paste0(names(df)[2:4],'_length')] <- lapply(df[2:4],str_length);
df;
##        V1      V2       V3       V4       V5 V2_length V3_length V4_length
## 1     jox      vr      qgm       dm ponznrpg         2         3         2
## 2      xy cskvquo  cwivjim pztjldas      sle         7         7         8
## 3  qbferj   uamts wkuylski        l   cwpoil         5         8         1
## 4 mszjuyf    wlgb  fsdgdgb   zmmetl    enbhf         4         7         6
## 5  dgkajw       i   wuulkv    ffpoc      xlu         1         6         5
## 6     mpm   rkxhl    rjhzq        q kbisiqvw         5         5         1

Data

set.seed(1L); NR <- 6L; NC <- 5L;
df <- as.data.frame(matrix(replicate(NR*NC,paste(collapse='',sample(letters,sample(1:8,1L),T)
)),NR));

Upvotes: 1

Related Questions