이벤트 기록이있는 데이터 프레임이 있으며 각 ID 번호의 마지막 이벤트가 해당 ID 번호의 시스템의 현재 값과 일치하는지 확인하여 무결성을 검사하려고합니다. 데이터는 요인으로 코딩됩니다.dplyr의 요인 변수 처리
df <-data.frame(ID=c(1,1,1,1,2,2,2,3,3),
current.grade=as.factor(c("Senior","Senior","Senior","Senior",
"Junior","Junior","Junior",
"Sophomore","Sophomore")),
grade.history=as.factor(c("Freshman","Sophomore","Junior","Senior",
"Freshman","Sophomore","Junior",
"Freshman","Sophomore")))
I가 current.grade
대해 그것을 grade.history
마지막 값을 추출하여 확인 dplyr
사용하려는 출력을
> df
ID current.grade grade.history
1 1 Senior Freshman
2 1 Senior Sophomore
3 1 Senior Junior
4 1 Senior Senior
5 2 Junior Freshman
6 2 Junior Sophomore
7 2 Junior Junior
8 3 Sophomore Freshman
9 3 Sophomore Sophomore
> str(df)
'data.frame': 9 obs. of 3 variables:
$ ID : num 1 1 1 1 2 2 2 3 3
$ current.grade: Factor w/ 3 levels "Junior","Senior",..: 2 2 2 2 1 1 1 3 3
$ grade.history: Factor w/ 4 levels "Freshman","Junior",..: 1 4 2 3 1 4 2 1 4
제공 : 다음 장난감 데이터 프레임은 최소한의 예이다
df.summary <- df %>%
group_by(ID) %>%
summarize(current.grade.last=last(current.grade),
grade.history.last=last(grade.history))
그러나 dplyr
은 인자를 정수로 변환하는 것으로 보이므로 다음을 얻습니다.
> df.summary
Source: local data frame [3 x 3]
ID current.grade.last grade.history.last
1 1 2 3
2 2 1 2
3 3 3 4
> str(df.summary)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 3 variables:
$ ID : num 1 2 3
$ current.grade.last: int 2 1 3
$ grade.history.last: int 3 2 4
원래 요소의 레벨 집합이 다르기 때문에 값이 일치하지 않습니다. dplyr
으로이 작업을 수행하는 올바른 방법은 무엇입니까?
나는 R
버전 3.1.1 및 dplyr
버전을 사용하고 0.3.0.2
데이터 세트를 만들 때'stringsAsFactors = FALSE'을 추가하면 코드가 정상적으로 작동합니다.'? data.frame'을 참조하십시오. 일반적인 이해를 위해 [여기] (http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information)를 참조하십시오. 요인, 또는 [여기에] (http://stackoverflow.com/questions/2851015/convert-data-frame-columns-from-factors-to-characters) –
@ 데이비드 OP (꽤 합리적으로) * 원하는 * 여기서 요인을 사용하십시오. –
@ KonradRudolph, 사실일지도 모릅니다. (배경을 읽지는 않았지만 실제 문제는 직면했습니다), 어떻게 합리적으로 * 합리적으로 정의 할 수 있는지 잘 모르겠습니다. –