Lost data frames after applying a function

Hi there. newby here...

I am trying to create a new data set where I have replaced the values in all rows for certain columns by applying a function to them. Ive done this with this code

df_new = as.data.frame(t(apply(df[c(3:5)], 1, function(x) x/sum(x))))

so dividing each cell in columns 3,4,5 by the summation of the rows of 3,4,5.

This works fine. However, I have now lost all of my other columns in the data set. some with string value others with numerical value. any help would be much appreciated.

#step 1, have some data
df <- mtcars

# keep track of the names
orignames <- names(df)
# pick the parts to work on
process <- df[c(3:5)] 
# set aside the parts not being worked on
notprocessed <- df[-c(3:5)]

# do work
df_new = as.data.frame(t(apply(process, 1, function(x) x/sum(x))))

# comine the work with the original parts not processed
final <- cbind(df_new,notprocessed)[,orignames]
1 Like

Thank you so much!. I really appreciate this as it cleans my code

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.