-3

我有一个包含字符串列的数据框 - 这些列中的每一列的格式为“xyz:x-dffh、dddd 和 stgL-fhgdf”

我需要在“和”这个词上分开 - 休息应该是原样

输入是具有 2 个此类列的数据框 - 输出将针对输入多个输出列中的每一列

这在 R 中可行吗?在 excel 中,我会使用文本到列 -

4

4 回答 4

2

如果“df”是您的数据框,您可以尝试从要拆分的原始列创建两个新列,将以下代码调整为您的数据:

df$newColumn1 <- lapply(strsplit(as.character(df$originalColumn), "and"), "[", 1)
df$newColumn2 <- lapply(strsplit(as.character(df$originalColumn), "and"), "[", 2)
于 2013-07-26T09:21:02.457 回答
1

您可以在基础 R 中尝试以下操作(类似于 bmartinez'z 答案,无需将列表分配给数据框):

df <- data.frame(originalColumn = c("dog and cat", "robots and raptors"))

do.call(rbind.data.frame, strsplit(as.character(df$originalColumn), "and"))

## > do.call(rbind.data.frame, strsplit(as.character(df$originalColumn), "and"))
##   c..dog.....robots... c...cat.....raptors..
## 1                 dog                    cat
## 2              robots                raptors

或者使用 qdap 包:

library(qdap)
colsplit2df(df, sep = "and")


## > colsplit2df(df, sep = "and")
##        X1       X2
## 1    dog       cat
## 2 robots   raptors
于 2013-07-26T12:09:24.200 回答
0

这对我有用 - 使用上面的输入和 SO 上的各种其他线程。我是 R 的新手,我的目标是将工作从 excel 迁移到 R。

# returns string w/o leading or trailing whitespace
trim <- function (x) gsub("^\\s+|\\s+$", "", x)

#--------------------------------------------------------------------------------
# OBJECTIVE - migrate this activity from excel + VBA to R
#
# split and find out max cols required - each element in dataframe is a list of
#variable length - objective is to convert it into individual columns with number of 
#columns = maximum size of list - for the rows with less number of entries the
#additional columns will contain "NA"
---------------------------------------------------------------------------------

temp_split<-strsplit(src.df$PREV,"and")
max_col=max(unlist(lapply(temp_split,length),recursive=TRUE))

# add to dataframe with fixed row and max_col
# keep columns empty - if no data

add_list <- function (x,max_col){
u_l <- unlist(x)
l<-length(unlist(x))
pad_col = max_col - l
r_l <- c(u_l, rep("NA",pad_col))
return(r_l)
}

test<-lapply(temp_split,add_list,max_col)
test_matrix<-data.frame(matrix(unlist(test,recursive=TRUE),nrow=NROW(src.df),byrow=T))

t.df<-test_matrix
c.df<-cbind(src.df,t.df)
于 2013-07-30T04:39:00.557 回答
0

这是对 Tyler Rinker 为解决几乎相同的问题而提供的出色答案的轻微修改。如果您想根据空格将 df 分成列(类似于 excel 中的列的文本)怎么办?

试试这个:
df <- data.frame(originalColumn = c("dog and cat", "robots and raptors")) dfSpace<-do.call(rbind.data.frame, strsplit(as.character(df[,1 ]), " ")) dfSpace

确保你和引号之间有一个空格。

于 2014-07-25T22:20:31.580 回答