How do I triple a column?
I am wondering how to multiply my data based on the appearance of the tripartite in the column.
t <- c(1,1,2,2,3,3,4,4,5,5,5,6,6,7,7,7,8,8)
mydf <- data.frame(t, 1:18)
I want to be able to grab only rows that match the triplet in column t, so that I can form a new dataframe of only those rows. It will look like this, where p is the vector of the strings I'm looking for:
p <- c(9,10,11,14,15,16)
myidealdf[p,]
Sorry if it's not clear, this is my first post
+3
Michael swift
source
to share
2 answers
This should do it
keeps <- unique(t)[table(as.factor(t)) == 3]
keeps <- t %in% keeps
mydf <- mydf[keeps, ]
+3
Shaun wilkinson
source
to share
Using the function rle
.
which(t %in% with(rle(t), values[lengths==3]))
[1] 9 10 11 14 15 16
0
Pierre lafortune
source
to share