reshape2
R: Reshaping Multiple Columns from Long to Wide
An option would be to replace the duplicated elements by ‘Letter’ to NA and then in the reshaped data, remove the columns that are all NA library(data.table) out <- dcast(setDT(sample_df)[, lapply(.SD, function(x) replace(x, duplicated(x), NA)), Letter], Letter ~ rowid(Letter), value.var = c(“Number”, “Fruit”)) nm1 <- out[, names(which(!colSums(!is.na(.SD))))] out[, (nm1) := NULL][] # Letter Number_1 Number_2 … Read more
Tidyr how to spread into count of occurrence [duplicate]
These are a few ways of many to go about it: 1) With library dplyr, you can simply group things and count into the format needed: library(dplyr) other %>% group_by(name) %>% summarise(N = sum(result == ‘N’), Y = sum(result == ‘Y’)) Source: local data frame [4 x 3] name N Y <fctr> <int> <int> 1 … Read more
how to pivot/unpivot (cast/melt) data frame? [duplicate]
I still can’t believe I beat Andrie with an answer. 🙂 > library(reshape) > my.df <- read.table(text = “Country 2001 2002 2003 + Nigeria 1 2 3 + UK 2 NA 1”, header = TRUE) > my.result <- melt(my.df, id = c(“Country”)) > my.result[order(my.result$Country),] Country variable value 1 Nigeria X2001 1 3 Nigeria X2002 2 … Read more
Convert a dataframe to presence absence matrix
One possibility: library(reshape2) df2 <- melt(df, id.var = “V1”) with(df2, table(V1, value)) # value # V1 A B C D E F # File1 1 1 1 0 0 0 # File2 1 1 0 1 0 0 # File3 0 0 0 0 1 1