2015-04-23 29 views
0

我有一个数据帧,其中包含多个不同长度的字符变量,我想将每个变量转换为列表,每个元素包含每个单词,并用空格分隔。分割和替换数据框中的字符变量R

说我的数据是这样的:

char <- c("This is a string of text", "So is this") 
char2 <- c("Text is pretty sweet", "Bet you wish you had text like this") 

df <- data.frame(char, char2) 

# Convert factors to character 
df <- lapply(df, as.character) 

> df 
$char 
[1] "This is a string of text" "So is this"    

$char2 
[1] "Text is pretty sweet"    "Bet you wish you had text like this" 

现在我可以用strsplit()由单个单词的分割每一列:

df <- transform(df, "char" = strsplit(df[, "char"], " ")) 
> df$char 
[[1]] 
[1] "This" "is"  "a"  "string" "of"  "text" 

[[2]] 
[1] "So" "is" "this" 

我想要做的就是创建一个循环或功能,这将允许我一次为这两列执行此操作,例如:

for (i in colnames(df) { 
    df <- transform(df, i = strsplit(df[, i], " ")) 
} 

但是,此p roduces错误:

Error in data.frame(list(char = c("This is a string of text", "So is this", : 
    arguments imply differing number of rows: 6, 8 

我也曾尝试:

splitter <- function(colname) { 
    df <- transform(df, colname = strsplit(df[, colname], " ")) 
} 

分路器(colnames(DF))

还告诉我:

Error in strsplit(df[, colname], " ") : non-character argument 

我很困惑,为什么对变换的调用适用于单个列,但不适用于在循环或函数中应用。任何帮助将非常感激!

+1

目前尚不清楚你想在这里做什么。为了将字符串保存为字符串,只需执行'df < - data.frame(char,char2,stringsAsFactors = FALSE)'。更重要的是,你是否意识到'lapply(df,as.character)'返回一个列表而不是数据框? 'transform'适用于数据框,不在列表中。最后,你期望的结果是什么?你想要一个'data.frame'作为'list'?这个问题很混乱。 –

回答

0

我不transform

char <- c("This is a string of text", "So is this") 
char2 <- c("Text is pretty sweet", "Bet you wish you had text like this") 
df <- data.frame(char, char2) 
# Convert factors to character 
df <- lapply(df, as.character) 

所需的输出,我把

lapply(df, strsplit, split= " ") 

要获得

$char 
$char[[1]] 
[1] "This" "is"  "a"  "string" "of"  "text" 

$char[[2]] 
[1] "So" "is" "this" 


$char2 
$char2[[1]] 
[1] "Text" "is"  "pretty" "sweet" 

$char2[[2]] 
[1] "Bet" "you" "wish" "you" "had" "text" "like" "this" 

而且亚历克斯提到:从你的代码中的第lapply df <- lapply(df, as.character)能通过将df <- data.frame(char, char2)更改为来消除

+0

你可以简化为'lapply(df,strsplit,split =“”)'。另外,不需要'lapply()'来获取字符;只需使用'df < - data.frame(char,char2,stringsAsFactors = FALSE)'。 –

+0

好主意!我会添加它 –