Home > Mobile >  Creating a function with a for loop into lapply
Creating a function with a for loop into lapply

Time:10-22

I am trying to use a simple function to perform an operation on a column of each dataframe of a list. Here is the data:

a<-LETTERS[1:6]
b<-1:6

df1<-as.data.frame(cbind(a,b))
df2<-as.data.frame(cbind(a,b))
df3<-as.data.frame(cbind(a,b))

df_list<-list(df1,df2,df3)

These are the names I want to use to rename the dataframes in the list:

df_names<-c("first","second","third")

By far, I have done this:

df2_list <- lapply(df_list, function(df_list) { 
  for(i in df_list[[i]]$b) { 
    df_double<-list((as.numeric(df_list[[i]]$b))*(2))
    names(df_double)<-df_names[i]
  } 
  df_list
} )

That gives me this error:

 Error in .subset2(x, i, exact = exact) : invalid subscript type 'list' 

But if I try to run separately these two commands, for instance on the first dataframe of the list, they do what I want:

df_double<-list((as.numeric(df_list[[1]]$b))*(2))
names(df_double)<-df_names[1]

I know I am missing something but I cannot see what... Thanks in advance!

CodePudding user response:

Use lapply to multiply the b column with 2 and use setNames to assign names.

setNames(lapply(df_list, function(x) transform(x, b = b * 2)), df_names)

#$first
#  a  b
#1 A  2
#2 B  4
#3 C  6
#4 D  8
#5 E 10
#6 F 12

#$second
#  a  b
#1 A  2
#2 B  4
#3 C  6
#4 D  8
#5 E 10
#6 F 12

#$third
#  a  b
#1 A  2
#2 B  4
#3 C  6
#4 D  8
#5 E 10
#6 F 12

For clarity, you may also do this in separate steps.

names(df_list) <- df_names
lapply(df_list, function(x) transform(x, b = b * 2))
  • Related