Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text manipulation using lapply()

Question

Are there other ways I may use lapply() to paste the column name for each element within each column in a data frame?

Problem

At the moment, I'm resorting to re-using lapply() for each column.

Reproducible Example

# 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

Thoughts

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.

like image 949
Cristian E. Nuno Avatar asked Sep 22 '26 09:09

Cristian E. Nuno


1 Answers

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
like image 88
KU99 Avatar answered Sep 25 '26 02:09

KU99