I would like to calculate how often changes between values happen by person-year combination (panel data). This mimics Stata's command xttrans. The transition between index 6 and 7 should not be included, since it is not a transition from within one person.
df = data.frame(id=c(1,1,1,1,1,1,1,2,2,2,2,2,2,2),
year=seq(from=2003, to=2009, by=1),
health=c(3,1,2,2,5,1,1,1,2,3,2,1,1,2))
Here is a base R solution to calculate transition counts by id groups:
with(df, do.call(`+`, tapply(health, id, function(x){
x <- factor(x, levels = min(health, na.rm = T):max(health, na.rm = T))
table(x[-length(x)], x[-1])
})))
# 1 2 3 4 5
# 1 2 3 0 0 0
# 2 1 1 1 0 1
# 3 1 1 0 0 0
# 4 0 0 0 0 0
# 5 1 0 0 0 0
library(tidyverse)
# Calculate the last health status for each id
df <- df %>%
group_by(id) %>%
mutate(lastHealth=lag(health)) %>%
ungroup()
# Count nunmber of existing transitions
transitions <- df %>%
group_by(health, lastHealth) %>%
summarise(N=n()) %>%
ungroup()
# Fill in the transition grid to include possible transitions that weren't observed
transitions <- transitions %>%
complete(health=1:5, lastHealth=1:5, fill=list(N=0))
# Present the transitions in the required format
transitions %>%
pivot_wider(names_from="health", values_from="N", names_prefix="health") %>%
filter(!is.na(lastHealth))
Related
I have a data.frame with more than 50 columns and 10,000 rows I want select those columns that are haveing 0 or 1 in them excluding other values in those columna
sample data.frame is as below:
dummy_df <- data.frame(
id=1:4,
gender=c(4,1,0,1),
height=seq(150, 180,by = 10),
smoking=c(3,0,1,0)
)
I want to select all those columns with 0 or 1 value and exclude other values like 4 in gender and 3 in smoking and as below
gender smoking
1 0
0 1
1 0
but I have 50 columns in actual data frame and I don't know which of them are having 0 or 1
What I'm trying is:
dummy_df %>% select_if(~ all( . %in% 0:1))
Is this useful for you?
dummy_df %>%
select(- c(id, height)) %>%
rowwise() %>%
filter(any(c_across() == 0)|any(c_across() == 1))
# A tibble: 3 x 2
# Rowwise:
gender smoking
<dbl> <dbl>
1 1 0
2 0 1
3 1 0
EDIT:
If you don't know in advance which cols contain 0 and/or 1, you can determine that in base R:
temp <- dummy_df[sapply(dummy_df, function(x) any(x == 0|x == 1))]
Now you can filter for rows with 0and/or 1:
temp %>%
rowwise() %>%
filter(any(c_across() == 0)|any(c_across() == 1))
I think it's more like a case of filter than select:
library(dplyr)
dummy_df %>%
filter(if_all(c(gender, smoking), ~ .x %in% c(0, 1)))
id gender height smoking
1 2 1 160 0
2 3 0 170 1
3 4 1 180 0
shift = c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3)
count =c(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7)
test <- cbind(shift,count)
So I am trying to mark every last row for every shift (so rows with count = c(8,10,7)with a binary 1 and every other row with 0. Right now I am thinking maybe that is possible with a left join but I am not quite sure. I would prefer not working with loops but rather use some techniques from dplyr. Thanks guys!
Assuming that you want to add a new 0/1 column last that contains a 1 in the last row of each shift and that the shifts are contiguous, here are two base R approaches:
transform(test, last = ave(count, shift, FUN = function(x) x == max(x)))
transform(test, last = +!duplicated(shift, fromLast = TRUE))
or with dplyr use mutate:
test %>%
as.data.frame %>%
group_by(shift) %>%
mutate(last = +(1:n() == n())) %>%
ungroup
test %>%
as.data.frame %>%
mutate(last = +!duplicated(shift, fromLast = TRUE))
Try this one
library(dplyr)
test %>%
as_tibble() %>%
group_by(shift) %>%
mutate(is_last = ifelse( row_number() == max(row_number()), 1, 0)) %>%
ungroup()
# A tibble: 25 x 3
shift count is_last
<dbl> <dbl> <dbl>
1 1 1 0
2 1 2 0
3 1 3 0
4 1 4 0
5 1 5 0
6 1 6 0
7 1 7 0
8 1 8 1
9 2 1 0
10 2 2 0
# … with 15 more rows
so I´m having a little trouble creating a new dataset by row-binding two "subsets" of an original datasets. I have implemented the following code, and it works fine. However it adds the rows of the second "subset" below the ones of the first "subset and doesn´t take into account the IDs.
rbind(df %>%
group_by(ID) %>%
filter(Var1 >=
((max(Var1)/100)*95)),
V_Dem_tracker_autocracies %>%
group_by(ID) %>%
filter(first_equal_to(Var2, 1)))
so what I get is the data structured like this:
ID Var2
1 0
1 0
1 0
2 0
2 0
2 0
1 1
2 1
however I would want it like this:
ID Var2
1 0
1 0
1 0
1 1
2 0
2 0
2 0
2 1
is there an easy solution getting to this? I appreciate all answers!
You can append arrange() to your pipe to wrap the new bound data frame.
rbind(df %>%
group_by(ID) %>%
filter(Var1 >= ((max(Var1)/100)*95)),
V_Dem_tracker_autocracies %>%
group_by(ID) %>%
filter(first_equal_to(Var2, 1))) %>%
arrange(ID)
If the order is incorrect, you can use desc(ID).
Given a dataframe:
v1_attr1 <- c(1,0,0,0,1,0,0,0,1,1) %>% as.integer ()
v1_attr2 <- c(0,1,0,0,1,1,1,1,1,1) %>% as.integer ()
v2_attr1 <- c(0,0,1,0,0,1,1,1,0,0) %>% as.integer ()
v2_attr2 <- c(0,0,0,1,0,1,1,1,0,0) %>% as.integer ()
df <- data.frame (v1_attr1, v1_attr2, v2_attr1, v2_attr2)
How can I set a filter for the attr of each v[[x]]?
I tried the following code to get the number of rows in each data.frame filtered by attr.
library(dplyr)
# create list for vs
list_vs <- list ("v1", "v2")
# set multiple attr filter for each v[[x]] to get the respective number of rows in each filtered data.frame (presented in a list)
filtered <- lapply (list_vs, function (x){
df %>% filter (noquote(paste0(list_vs[[x]], "_attr1")) == 1 | noquote(paste0(list_vs[[x]], "_attr2")) == 1) %>%
nrow ()
})
Although this code doesn't return an error, the result for filtered[[x]] is always 0. How do I need to set the filter arguments correctly to get the desired number of rows in each data.frame? I used noquote because otherwise filtering arguments would be pasted in quotes.
One dplyr and purrr option could be:
map(.x = list_vs,
~ df %>%
filter_at(vars(starts_with(.x)), any_vars(. == 1)))
[[1]]
v1_attr1 v1_attr2 v2_attr1 v2_attr2
1 1 0 0 0
2 0 1 0 0
3 1 1 0 0
4 0 1 1 1
5 0 1 1 1
6 0 1 1 1
7 1 1 0 0
8 1 1 0 0
[[2]]
v1_attr1 v1_attr2 v2_attr1 v2_attr2
1 0 0 1 0
2 0 0 0 1
3 0 1 1 1
4 0 1 1 1
5 0 1 1 1
An option is to convert to 'long' format with pivot_longer by automatically picking up the patterns from the column names, and then do a group_by, filter_at
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = everything(), names_sep = "_",
names_to = c('group', '.value' )) %>%
group_by(group) %>%
filter_at(vars(-group_cols()), any_vars(. == 1))
I have data that looks like this:
library(dplyr)
d<-data.frame(ID=c(1,1,2,3,3,4), Quality=c("Good", "Bad", "Ugly", "Good", "Good", "Ugly"), Area=c("East", "North", "North", "South", "East", "North"))
What I'd like to do is create one new column for each unique value in Quality and populate it with whether the ID matches that value and then aggregate the ID's. I want to do the same for Area.
This is what I have for when Quality == Good:
d$Quality.Good <- 0
d$Quality.Good[d$Quality=="Good"] <- 1
e <- d %>%
group_by(ID) %>%
summarise(n=n(), MAX.Quality.Good = max(Quality.Good))
e
Output
A tibble: 4 x 3
ID MAX.Quality.Good
<dbl> <dbl>
1 1 1
2 2 0
3 3 1
4 4 0
Is it possible to build a function that will loop through each character column and build an indicator column for Good, Bad, Ugly, North, East, South instead of copy pasting the above many more times?
Here's where I'm stuck:
library(stringr)
#vector of each Quality
e <-d %>%
group_by(Quality) %>%
summarise(n=n()) %>%
select(Quality)
e<-as.data.frame(e)
#create new column names
f <- str_c(names(e),".",e[,1])
#initialize list of new columns
d[f] <- 0
#I'm stuck after this...
Thank you!
We can do this in base R using table by replicating the 'ID' column by the number of columns of dataset minus 1, and pasteing the column names with the unlisted values (excluding the 'ID' column)
table(rep(d$ID, 2), paste0(names(d)[-1][col(d[-1])], unlist(d[-1])))
# AreaEast AreaNorth AreaSouth QualityBad QualityGood QualityUgly
# 1 1 1 0 1 1 0
# 2 0 1 0 0 0 1
# 3 1 0 1 0 2 0
# 4 0 1 0 0 0 1
or with tidyverse, gather into 'long' format, unite the 'key', 'val' columns to a single column, get the distinct rows, and spread into 'wide' format after creating a column of 1s.
library(tidyverse)
gather(d, key, val, -ID) %>%
unite(kv, key, val) %>%
distinct %>%
mutate(n = 1) %>%
spread(kv, n, fill = 0)
#ID Area_East Area_North Area_South Quality_Bad Quality_Good Quality_Ugly
#1 1 1 1 0 1 1 0
#2 2 0 1 0 0 0 1
#3 3 1 0 1 0 1 0
#4 4 0 1 0 0 0 1
1) Base R Create the model matrix for each column (using function make_mm) and bind them together as a data frame m. Finally aggregate on ID. No packages are used.
make_mm <- function(nm, data) model.matrix(~ . - 1, data[nm])
m <- do.call("data.frame", lapply(names(d)[-1], make_mm, d))
with(d, aggregate(. ~ ID, m, max))
giving:
ID QualityBad QualityGood QualityUgly AreaEast AreaNorth AreaSouth
1 1 1 1 0 1 1 0
2 2 0 0 1 0 1 0
3 3 0 1 0 1 0 1
4 4 0 0 1 0 1 0
2) dplyr/purrr This could alternately be written as the following which is close to the code in the question but generalizes to all required columns. Note that here we make model data frames using make_md rather than making model matrices with make_mm. Also note that the dot in group_by(m, ID = .$ID) refers to d and not to m.
library(dplyr)
library(purrr)
make_md <- function(nm, data) {
data %>%
select(nm) %>%
model.matrix(~ . - 1, .) %>%
as.data.frame
}
d %>% {
m <- map_dfc(names(.)[-1], make_md, .)
group_by(m, ID = .$ID) %>%
summarize_all(max) %>%
ungroup
}