简体   繁体   English

如何将一个字符串拆分为多列?

[英]How to split a string into multiple columns?

I have a string that looks like this:我有一个看起来像这样的字符串:

# character string
string <- "lambs:    cows: 281        chickens: 20   goats: 3     trees: 13"

I want to create a dataframe that looks like this:我想创建一个看起来像这样的 dataframe:

# structure
lambs <- NA
cows <- 281
chickens <- 20
goats <- 3
trees <- 13

# dataframe
df <- 
  cbind(lambs, cows, chickens, goats, trees)  %>% 
  as.data.frame()

This is what I have tried so far:这是我到目前为止所尝试的:

# split string
test <- strsplit(string, " ")
test

The data is quite unclean so the spacing isn't always consistent, and sometimes there are lambs and sometimes there are no lambs (as in: "lamb: 5 cow: 50" and "lamb: cow: 40" . What is the easiest way to do this using tidyverse?数据很不干净,所以间距并不总是一致的,有时有羔羊,有时没有羔羊(如: "lamb: 5 cow: 50""lamb: cow: 40" 。什么是最简单的如何使用 tidyverse 做到这一点?

You can use str_match_all and pass the pattern to extract.您可以使用str_match_all并传递要提取的模式。

tmp <- stringr::str_match_all(string, '\\s*(.*?):\\s*(\\d+)?')[[1]][, -1]
data <- type.convert(data.frame(tmp), as.is = TRUE)

#        X1  X2
#1    lambs  NA
#2     cows 281
#3 chickens  20
#4    goats   3
#5    trees  13

This divides data into two columns where the first column is everything before colon ( : ) except whitespace and the second column is number followed after it.这将数据分成两列,其中第一列是冒号 ( : ) 之前的所有内容,除了空格,第二列是后面的数字。 I have made the number part as optional so as to accommodate cases like 'lambs' which do not have number.我已将数字部分设为可选,以适应没有数字'lambs'类的情况。

Try this:尝试这个:

gre <- gregexpr("\\b([A-Za-z]+:\\s*[0-9]*)\\b", string)
regmatches(string, gre)
# [[1]]
# [1] "lambs:    "   "cows: 281"    "chickens: 20" "goats: 3"     "trees: 13"   
lapply(regmatches(string, gre), strcapture, pattern = "(.*):(.*)", proto = list(anim = character(0), n = character(0)))
# [[1]]
#       anim    n
# 1    lambs     
# 2     cows  281
# 3 chickens   20
# 4    goats    3
# 5    trees   13
frames <- lapply(regmatches(string, gre), strcapture,
                 pattern = "(.*):(.*)", proto = list(anim = character(0), n = character(0)))

If you have multiple strings (and not just one), then this ensure that each string is processed and then all data is combined.如果您有多个字符串(而不仅仅是一个),那么这将确保处理每个字符串,然后合并所有数据。

alldat <- do.call(rbind, frames)
alldat$n <- as.integer(alldat$n)
alldat
#       anim   n
# 1    lambs  NA
# 2     cows 281
# 3 chickens  20
# 4    goats   3
# 5    trees  13

If you instead really need the data in a "wide" format, then如果您确实需要“宽”格式的数据,那么

do.call(rbind, lapply(frames, function(z) do.call(data.frame, setNames(as.list(as.integer(z$n)), z$anim))))
#   lambs cows chickens goats trees
# 1    NA  281       20     3    13

You can try read.table .你可以试试read.table The "no lambs" issue can be solved by putting in a zero with gsub . “没有羔羊”问题可以通过在gsub中输入零来解决。

r <- na.omit(unlist(read.table(text=gsub(": ", " 0", string), sep=" ")))
r <- replace(r, r == 0, NA)

## long format
type.convert(as.data.frame(matrix(r, ncol=2, byrow=TRUE)), as.is=TRUE)
#         V1  V2
# 1    lambs  NA
# 2     cows 281
# 3 chickens  20
# 4    goats   3
# 5    trees  13

## wide format
setNames(type.convert(r[seq(r) %% 2 == 0]), r[seq(r) %% 2 == 1])
# lambs     cows chickens    goats    trees 
#    NA      281       20        3       13 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM