2012-11-27 3 views
0

data.frame이 있습니다. col2에 값을 할당하기 위해 2, 3, 4 열의 값을 사용하려고합니다. 이것이 가능한가?ifelse : 1 열에서 다른 열 및 여러 문으로 조건 할당

dat<-data.frame(col1=c(1,2,3,4,5), col2=c(1,2,3,4,"U"), col3=c(1,2,3,"U",5), col4=c("U",2,3,4,5)) 
dat1=data.frame(col1=ifelse(dat$col2=="U"|dat$col3=="U"|dat$col4=="U", dat$col1=="U", dat$col1)) 

col1 
0 
2 
3 
0 
0 

왜 나는 U가 있어야하는가?

+2

'ifelse' 덜 제공 : TRUE


또한 T/F를 활용할 수 있습니다에 대한 FALSE 0, 1 코드를 정리하기 위해 1/0로 평가 받고 직관적 인 결과보다 자주. 대신'if {} else {}'를 사용하는 것이 좋습니다. –

답변

4

ifelse 기능 내에 할당하지 마십시오.

dat1=data.frame(col1=ifelse(dat$col2=="U"|dat$col3=="U"|dat$col4=="U", 
       "U", 
       dat$col1)) 
dat1 
    col1 
1 U 
2 2 
3 3 
4 U 
5 U 
+0

왜'ifelse' 함수로 할당하지 않습니까? OP 질문의 배정 부분에는 문제가 없습니다. –

+0

아래 코드와 같이 질문을 읽었습니다. 'ifelse'내에서 할당하면 종종 결과가 기대에 미치지 못합니다 ... 'dat1 = data.frame (col1 = ifelse (dat $ col2 == "U"| dat $ col3 == "U"| dat $ col4 == "U", $ col1 <- "U", dat $ col1))' – Justin

+0

gotcha, ifelse 문을 __inside__로 지정하지 마십시오. 아마도 그것을 반영하기 위해 답을 편집하십시오. (지금 당장은 ifelse를 사용해서 할당하지 말아야한다고 들린다.'x <- ifelse (.) ' –

0

any()이 많은

head(dat) 
    col1 col2 col3 col4 
1 1 1 1 U 
2 2 2 2 2 
3 3 3 3 3 
4 4 4 U 4 
5 5 U 5 5 

apply(dat,1, function(x)any(x=='U')) 
[1] TRUE FALSE FALSE TRUE TRUE 
dat[apply(dat,1, function(x)any(x=='U')), 1] <-'U' 

dat 
    col1 col2 col3 col4 
1 U 1 1 U 
2 2 2 2 2 
3 3 3 3 3 
4 U 4 U 4 
5 U U 5 5 
0

깔끔한 쉬운 방법이 될 것 같은 일을한다 :

dat$col1[as.logical(rowSums(dat[-1]=="U"))] <- "U" 


    col1 col2 col3 col4 
1 U 1 1 U 
2 2 2 2 2 
3 3 3 3 3 
4 U 4 U 4 
5 U U 5 5 
1

당신이 아마 원하는 것은이 사용된다 :

dat1 <- data.frame(col1=ifelse(dat$col2=="U"|dat$col3=="U"|dat$col4=="U", "U", dat$col1)) 
    # I changed the dat$col1=="U" to just "U" 


질문이 "Why am I getting a 0 where a U should be?" 인 경우 대답은 ifelse(.) 문의 if-TRUE 부분에 할당 한 내용에 있습니다.

귀하의 ifelse 문은 본질적 ifelse 테스트 TRUE로 평가 때

if any of columns 2 through 4 are U 
then assign the value of `does column 1 == "U"` <-- Not sure if this is what you want 
else assign the value of column 1 

그래서, 당신이 반환받을 것은 col1=="U"의 값이지만, 정수 강요했다. 예 :

# using the fact that rowSums(dat[2:4]=="U") will be 0 when "U" is not in any column: 
ifelse(rowSums(dat[2:4]=="U")>0, "U", dat$col1)