dplyr mutate rowSums 계산 또는 사용자 지정 함수
rowSums
다음과 같이 행 계산의 종류에서 새 변수를 변경하려고 합니다.
iris %>%
mutate_(sumVar =
iris %>%
select(Sepal.Length:Petal.Width) %>%
rowSums)
결과는 "sumVar"가 첫 번째 값 (10.2)으로 잘립니다.
Source: local data frame [150 x 6]
Groups: <by row>
Sepal.Length Sepal.Width Petal.Length Petal.Width Species sumVar
1 5.1 3.5 1.4 0.2 setosa 10.2
2 4.9 3.0 1.4 0.2 setosa 10.2
3 4.7 3.2 1.3 0.2 setosa 10.2
4 4.6 3.1 1.5 0.2 setosa 10.2
5 5.0 3.6 1.4 0.2 setosa 10.2
6 5.4 3.9 1.7 0.4 setosa 10.2
..
Warning message:
Truncating vector to length 1
rowwise
적용 해야합니까 ? 또는 이러한 종류의 계산에 사용할 올바른 동사는 무엇입니까?
편집하다:
더 구체적으로, 인라인 사용자 정의 함수를 실현하는 방법이 dplyr
있습니까?
다음과 같이 할 수 있는지 궁금합니다.
iris %>%
mutate(sumVar = colsum_function(Sepal.Length:Petal.Width))
이것은 해결 방법에 더 가깝지만 사용할 수 있습니다.
iris %>% mutate(sumVar = rowSums(.[1:4]))
주석에 쓰여진 것처럼 select
, 예를 들어 요약하려는 열을 얻기 위해 mutate 내부를 사용할 수도 있습니다.
iris %>%
mutate(sumVar = rowSums(select(., contains("Sepal")))) %>%
head
또는
iris %>%
mutate(sumVar = select(., contains("Sepal")) %>% rowSums()) %>%
head
더 복잡한 방법은 다음과 같습니다.
iris %>% select(Sepal.Length:Petal.Width) %>%
mutate(sumVar = rowSums(.)) %>% left_join(iris)
@docendodiscimus의 댓글을 답변으로 추가합니다. 그에게 +1!
iris %>% mutate(sumVar = rowSums(select(., contains("Sepal"))))
I am using this simple solution, which is a more robust modification of the answer by Davide Passaretti:
iris %>% select(Sepal.Length:Petal.Width) %>%
transmute(sumVar = rowSums(.)) %>% bind_cols(iris, .)
(But it requires a defined row order, which should be fine, unless you work with remote datasets perhaps..)
You can also use a grep in place of contains
or matches
, just in case you need to get fancy with the regular expressions (matches
doesn't seem to much like negative lookaheads and the like in my experience).
iris %>% mutate(sumVar = rowSums(select(., grep("Sepal", names(.)))))
ReferenceURL : https://stackoverflow.com/questions/27354734/dplyr-mutate-rowsums-calculations-or-custom-functions
'Nice programing' 카테고리의 다른 글
Gnome 터미널의 배경 설정을 재정의하는 Vim 색 구성표 (0) | 2021.01.10 |
---|---|
명령 출력을 bash의 변수에 저장할 때 줄 바꿈을 유지하는 방법은 무엇입니까? (0) | 2021.01.10 |
Docker 컨테이너에서 영구적으로 PATH 환경 변수 업데이트 (0) | 2021.01.10 |
msi 설치 후 exe를 실행 하시겠습니까? (0) | 2021.01.10 |
"if"필터가있는 반복자에 대한 한 줄 for 루프? (0) | 2021.01.10 |