我是 R 的新手。我有一列(是的,只有一列)有 200 行,其元素是用逗號分隔的字串。
實際資料:
"A, B, C, D"
"1, 10, 13, 4"
"0, 1, 6, 1"
"9, 3, 3, 0"
...
從這一列中,我想生成以下資料框:
A B C D
1 10 13 4
0 1 6 1
9 3 3 0
...
其中“A”、“B”、“C”、“D”是該資料框的列標題,行也分別用逗號分割為每個創建的列。我怎樣才能在 R 中實作這一目標?
uj5u.com熱心網友回復:
嘗試read.table如下
> read.table(text = df$Col1, header = TRUE, sep = ",")
A B C D
1 1 10 13 4
2 0 1 6 1
3 9 3 3 0
uj5u.com熱心網友回復:
這是一種替代方法:
library(tidyverse)
library(janitor)
str_split_fixed(df$V1, ", ", 4) %>%
row_to_names(.,1) %>%
as_tibble()
A B C D
<chr> <chr> <chr> <chr>
1 1 10 13 4
2 0 1 6 1
3 9 3 3 0
資料:
structure(list(V1 = c("A, B, C, D", "1, 10, 13, 4", "0, 1, 6, 1",
"9, 3, 3, 0")), class = "data.frame", row.names = c(NA, -4L))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396866.html
上一篇:用逗號將字串拆分成列
