1

I'm a beginner in R and I am stuck with the following..

df <- tibble( id = c(01, 02), a = c(0.44, 0.42), b = c(1, 0.42), c = c(NaN, 0.71), d = c(0.75, 0), e = c(0.66, 0.75), f = c(0.5, 0.22), g = c(1, NaN), h = c(0.8, NaN) ) 

I wonder how I can mutate a column that counts the number of cases of cells >0 - separately for the columns a:d and e:h (&rowwise)

I have been thinking of something like this..

df1 <- df %>% rowwise() %>% mutate(casesatod = length(which(., > 0), na.rm = TRUE), casesetoh = length(which(., > 0), na.rm = TRUE)) 

Of course, this code is not complete but to give you an idea of what I was thinking of..

I'd really looking forward to receiving help from you !

Thanks in advance !

0

1 Answer 1

2

An option would be rowSums after selecting subset of columns from the dataset. It would be more efficient than rowwise as it is vectorized

library(dplyr) df %>% mutate(casesatod = rowSums(.[2:5] > 0, na.rm = TRUE), casesetoh = rowSums(.[6:9] > 0, na.rm = TRUE)) 

If we need to use column names for selecting, use select

df %>% mutate(casesatod = rowSums(select(., a:d) > 0, na.rm = TRUE), casesetoh = rowSums(select(., e:h) > 0, na.rm = TRUE)) # A tibble: 2 x 11 # id a b c d e f g h casesatod casesetoh # <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #1 1 0.44 1 NaN 0.75 0.66 0.5 1 0.8 3 4 #2 2 0.42 0.42 0.71 0 0.75 0.22 NaN NaN 3 2 
Sign up to request clarification or add additional context in comments.

6 Comments

@JoB seems like you have group_by attribute, try df %>% ungroup %>% and then uses mutate with correct index
Thanks a lot ! Unfortunately, I repeatedly get an error message when I try to apply your code to my original dataset which consists of 82 rows.. "Fehler: Column casesS11toS14 must be length 2 (the group size) or one, not 156". Do you happen to have an explanation ?
@JoB Is it the error even after ungroup I don't think so
@JoB As I mentioend, I can reproduce the error whn there is a group_by and if it is ungrouped, it will go away iris %>% group_by(Species) %>% mutate(new = rowSums(.[1:3] > 0)) Error: Column new` must be length 50 (the group size) or one, not 150`
WIth ungroup iris %>% group_by(Species) %>% ungroup %>% mutate(new = rowSums(.[1:3] > 0)) # A tibble: 150 x 6 Sepal.Length Sepal.Width Petal.Length Petal.Width Species new <dbl> <dbl> <dbl> <dbl> <fct> <dbl> 1 5.1 3.5 1.4 0.2 setosa 3
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.