[英]Character vector to dataframe in R
I have the following character vector:我有以下字符向量:
da <- c(" 1 1 0 0 0 0 0 7.071", " 2 0 0 1 0 1 1 3.033", " 3 1 1 0 0 1 0 4.095")
I would like it to become a dataframe where each split value is a new cell and each element in the character is a new row.我希望它成为 dataframe ,其中每个拆分值都是一个新单元格,字符中的每个元素都是一个新行。 So it would become:
所以它会变成:
1 | 1 | 0 | 0 | 0 | 0 | 0 | 7.071
2 | 0 | 0 | 1 | 0 | 1 | 1 | 3.033
3 | 1 | 1 | 0 | 0 | 1 | 0 | 4.095
Coeercing straight to a dataframe or a list then a dataframe does not work.直接强制到 dataframe 或列表然后 dataframe 不起作用。
read.table
+ paste
read.table
+ paste
df <- read.table(text = paste(da,sep = "\n"),
header = FALSE)
strsplit
+ rbind
, eg,strsplit
+ rbind
,例如,df <- as.data.frame(do.call(rbind,strsplit(trimws(da)," ")))
such that这样
> df
V1 V2 V3 V4 V5 V6 V7 V8
1 1 1 0 0 0 0 0 7.071
2 2 0 0 1 0 1 1 3.033
3 3 1 1 0 0 1 0 4.095
First you want to trim the leading whitespace using stringr::str_trim
, and then split each substring up by the space delim using stringr::str_split
.首先,您要使用
stringr::str_trim
修剪前导空格,然后使用stringr::str_split
将每个 substring 拆分为空格分隔符。 This returns a nested list that you can unlist, convert to a matrix and then data.frame.这将返回一个嵌套列表,您可以将其取消列出,转换为矩阵,然后转换为 data.frame。
da <- c(" 1 1 0 0 0 0 0 7.071", " 2 0 0 1 0 1 1 3.033", " 3 1 1 0 0 1 0 4.095")
a = stringr::str_split(stringr::str_trim(da), pattern=" ")
df = data.frame(matrix(unlist(a), nrow=length(a), byrow=T))
Not terribly elegant, but it works.不是很优雅,但它确实有效。
library(dplyr)
library(stringr)
da <- da %>%
str_trim() %>%
str_split(., " ") %>%
data.frame %>%
t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.