데이터 프레임에서 하나의 긴 행을 얻는 사람의 변수 목록이 있습니다.이 레코드를 더 의미있는 형식으로 재구성하는 데 관심이 있습니다. 내 원시 데이터는 다음과 같습니다데이터 프레임에서 하나의 긴 행을 개별 레코드로 변환합니다.
,
df <- data.frame(name1 = "John Doe", email1 = "[email protected]", phone1 = "(444) 444-4444", name2 = "Jane Doe", email2 = "[email protected]", phone2 = "(444) 444-4445", name3 = "John Smith", email3 = "[email protected]", phone3 = "(444) 444-4446", name4 = NA, email4 = "[email protected]", phone4 = NA, name5 = NA, email5 = NA, phone5 = NA)
df
# name1 email1 phone1 name2 email2 phone2
# 1 John Doe [email protected] (444) 444-4444 Jane Doe [email protected] (444) 444-4445
# name3 email3 phone3 name4 email4 phone4 name5
# 1 John Smith [email protected] (444) 444-4446 NA [email protected] NA NA
# email5 phone5
# 1 NA NA
나는 이런 형식으로 구부러 노력하고,
df_transform <- structure(list(name = structure(c(2L, 1L, 3L, NA, NA), .Label = c("Jane Doe",
"John Doe", "John Smith"), class = "factor"), email = structure(c(3L,
1L, 4L, 2L, NA), .Label = c("[email protected]", "[email protected]",
"[email protected]", "[email protected]"), class = "factor"), phone = structure(c(1L,
2L, 3L, NA, NA), .Label = c("(444) 444-4444", "(444) 444-4445",
"(444) 444-4446"), class = "factor")), .Names = c("name", "email",
"phone"), class = "data.frame", row.names = c(NA, -5L))
df_transform
# name email phone
# 1 John Doe [email protected] (444) 444-4444
# 2 Jane Doe [email protected] (444) 444-4445
# 3 John Smith [email protected] (444) 444-4446
# 4 <NA> [email protected] <NA>
# 5 <NA> <NA> <NA>
그것은 다섯 개 기록은 항상 아니라고 추가되어야한다 1에서 99 사이의 숫자가 될 수 있습니다. reshape2
의 melt
과`t() 1로 시도했지만 복잡합니다. 내가 모르는 방법을 알고 있다고 상상해보십시오. 당신은 올바른 궤도에있어
감사합니다, 나는 당신의 대답을 좋아하고 당신은 오직베이스 -R을 사용하고 있다고 생각합니다. –
'reshape()'의 다양한 인수는 해당 reshape2 솔루션보다 문제에 더 적합하지만 행렬 재 형성과'tapply' 솔루션은 추가 된 것 중 가장 간단한 것일 수 있습니다. –