I have three dataframes in R, df1, df2, df3 that contain different data, however, the last column contains my target variable for each dataset. However, in each instance, the last column is an integer and I want it to be a factor. I know I can do the following code to convert the column into a factor:
df1[,'lascoldf1'] <-factor(df1[,'lastcoldf1'])
df2[,'lascoldf2'] <-factor(df2[,'lastcoldf2'])
df3[,'lascoldf3'] <-factor(df3[,'lastcoldf3'])
However, this seems a little inefficient. Also, the last colname isn't always the same name, and each dataset has a different number of columns, so I just need a way of referencing the last column. I've found this way so would probably need something like the following pseudo-code:
for (df in c(df1,df2,df3)){
index = df[,ncol(df)]
lapply(df[,index] , factor)
}
However, I can't seem to get it to work properly.
question from:
https://stackoverflow.com/questions/65841901/convert-the-last-column-of-several-dataframes-to-a-factor-in-r 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…