Cri*_*uno 3 text r lapply dataframe
我可以使用其他方法lapply()粘贴数据框中每列中每个元素的列名吗?
目前,我正在lapply()为每一栏重新使用.
# 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
Run Code Online (Sandbox Code Playgroud)
目前,我认为这种方法涉及太多的复制和粘贴.如果我存储colnames( df )为一个字符向量,我不知道如何使用该对象 - 只使用lapply()一次 - 来获得我想要的结果.我认为它涉及在我提供的功能中使用多个计数器FUN,但我不确定如何继续.
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
Run Code Online (Sandbox Code Playgroud)