Are there other ways I may use lapply() to paste the column name for each element within each column in a data frame?
At the moment, I'm resorting to re-using lapply() for each column.
# create data
df <- data.frame(
Chicago_Has = c("Lou Malnati's", "Wrigley Field", "CTA" )
, Seattle_Has = c("Piroshky Piroshky", "Safeco Field", "KCMT" )
, stringsAsFactors = FALSE
)
# paste column name into each element
# within each column
df[ "Chicago_Has" ] <- lapply( X = df[ "Chicago_Has" ]
, FUN = function(i) paste( "Chicago_Has", i, sep = " " )
)
df[ "Seattle_Has" ] <- lapply( X = df[ "Seattle_Has" ]
, FUN = function(i) paste( "Seattle_Has", i, sep = " ")
)
# examine the desired result of the data frame
df
# Chicago_Has Seattle_Has
# 1 Chicago_Has Lou Malnati's Seattle_Has Piroshky Piroshky
# 2 Chicago_Has Wrigley Field Seattle_Has Safeco Field
# 3 Chicago_Has CTA Seattle_Has KCMT
At the moment, I think this method involves too much copying and pasting. If I store colnames( df ) as a character vector, I don't know how I would use that object - while only using lapply() once - to obtain my desired results. I think it involves using multiple counters in the function I'm supplying in FUN, but am unsure how to proceed.
df[]=Map(paste,names(df),df)
df
Chicago_Has Seattle_Has
1 Chicago_Has Lou Malnati's Seattle_Has Piroshky Piroshky
2 Chicago_Has Wrigley Field Seattle_Has Safeco Field
3 Chicago_Has CTA Seattle_Has KCMT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With