题
我还有其他方法可以使用 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
想法
目前,我认为这种方法涉及太多的复制和粘贴。如果我存储
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
关于r - 使用 lapply() 进行文本操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493579/