我正在嘗試格式化我的資料,使其寬而不是長,我似乎遇到了將其從串列轉換為任何可以讓我改變其形式的問題。
library(stringr)
library(tidyr)
library(dplyr)
A <- as.list(c("v", "w", "x", "y", "NA"))
str(A)
X <- 5
G <- str_split_fixed(A, ", ", X)
G <- as.data.frame(A)
G <- G[-c(182, 183)] #irrelevant on example data my actual data is much longer
P <- G
P <- gsub("NA", "Z", as.character(P))#also irrelavent for example data
P <- str_split_fixed(P, ", ", X)
colnames(P) <- c("A", "B", "C", "D", "E")
Titles <- c("Time_Modifier", "Times", "Scrambles", "Blank", "ID")
T.1 <- strsplit(Titles, " ")
n <- nrow(P)
n/5
L <- rep(T.1, n/5)
T.T <- cbind(P, L)
T.T.1 <- subset(T.T, select = -c(B, C, D, E))
T.T.1 <- subset(T.T.1, L != "Blank")
我曾嘗試使用 pivot_wider() 出現此錯誤
pivot_wider(T.T.1,
names_from = L,
values_from = A
)
UseMethod("pivot_wider") 中的錯誤:沒有適用于 'pivot_wider' 的方法應用于類 "c('matrix', 'array', 'list')"
我也嘗試過使用 pivot_wider_spec() ,但我遇到了類似的錯誤。這讓我認為 TT1 被存盤為一個串列;哪個低,看哪。但是,我似乎無法將 TT1 更改為 pivot_wider 喜歡的資料型別。
我曾嘗試使用 as.data.frame()、as.character 以及我能想到或找到的幾乎所有其他東西來轉換 TT1。
T.T.1 <- as.data.frame(T.T.1)
pivot_wider(T.T.1,
names_from = L,
values_from = A
)
錯誤:必須使用有效的下標向量對列進行子集化。x 下標型別錯誤list。i 必須是數字或字符。
T.T.1 <- as.character(T.T.1)
pivot_wider(T.T.1,
names_from = L,
values_from = A
)
UseMethod("pivot_wider") 中的錯誤:沒有適用于“pivot_wider”的方法應用于“character”類的物件
非常感謝任何和所有幫助。
uj5u.com熱心網友回復:
pivot_wider 需要一個資料框:
因此使用as_tibbleor as.data.framebefore T.T.1which 是一個矩陣(您可以檢查class(T.T.1):
你會得到一個清單。如果您想unnest從tidyr包中查看串列使用。
pivot_wider(as_tibble(T.T.1),
names_from = L,
values_from = A
) %>%
unnest(cols = c(Time_Modifier, Times, Scrambles, ID))
輸出:
Time_Modifier Times Scrambles ID
<chr> <chr> <chr> <chr>
1 v w x Z
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/391183.html
