[英]How to manipulate or transpose a dataset for use in R or SPSS
我需要將原始數據(csv)操作為寬格式,以便我可以在R或SPSS中進行分析。
它看起來像這樣:
1,age,30
1,race,black
1,scale_total,35
2,age,20
2,race,white
2,scale_total,99
理想情況下它看起來像:
ID,age,race,scale_total, etc
1, 30, black, 35
2, 20, white, 99
我將值添加到原始數據的頂行(ID,問題,響應)並嘗試了轉換函數,但我相信這些聚合數據而不僅僅是轉換它:
data_mod <- cast(raw.data2, ID~Question, value="Response")
Aggregation requires fun.aggregate: length used as default
我們需要創建一個序列列來處理重復的行,默認情況下會導致聚合到length
library(data.table)
dcast(setDT(df1), ID + rowid(Question) ~ Question, value.var = 'Response')
注意:示例數據清楚地工作(給出預期的輸出)而不使用序列列。
dcast(setDT(df1), ID ~ Question)
# ID age race scale_total
#1: 1 30 black 35
#2: 2 20 white 99
因此,這是應用於具有重復行的完整數據集的情況
df1 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L), Question = c("age",
"race", "scale_total", "age", "race", "scale_total"), Response = c("30",
"black ", "35", "20", "white", "99")), class = "data.frame",
row.names = c(NA, -6L))
你可以用tidyr
......
library(tidyr)
df<-read.csv(text="1,age,30
1,race,black
1,scale_total,35
2,age,20
2,race,white
2,scale_total,99", header=FALSE, stringsAsFactors=FALSE)
df %>% spread(key=V2,value=V3)
V1 age race scale_total
1 1 30 black 35
2 2 20 white 99
對於SPSS:
data list list/ID (f5) Question Response (2a20).
begin data
1 "age" "30"
1 "race" "black"
1 "scale_total" "35"
2 "age" "20"
2 "race" "white"
2 "scale_total" "99"
end data.
casestovars /id=id /index=question.
請注意,結果變量age
和scale_total
將是字符串變量 - 在進一步轉換之前,您必須將它們轉換為數字:
alter type age scale_total (f8).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.