2

I am looking to create new columns in an R data frame based on characters stored in an existing column. For example, suppose I have the following data frame:

> df = data.frame(retroid = c("loftk001", "vizq001"), pitchcount = c("BBBCCFB", "CCX"))
> df
   retroid pitchcount
1 loftk001    BBBCCFB
2  vizq001        CCX

I want to create new columns, "p1, p2, p3", etc. such that it looks like

   retroid pitchcount p1 p2 p3 p4 p5 p6 p7
1 loftk001    BBBCCFB B  B  B  C  C  F  B
2  vizq001        CCX C  C  X

One of the potential problems I am facing is that the strings stored under column "pitchcount" are of variable length. As in the case above, if the string in "pitchcount" has less characters than the maximum, I just want empty values in the corresponding columns.

Is there a fast way to do this in R?

Thank you in advance!

2 Answers 2

3

You could use cSplit, where df is your original data.

library(splitstackshape)

cs <- cSplit(df[2], "pitchcount", "", stripWhite=FALSE, type.convert=FALSE)
setnames(cs, names(cs), sub(".*_", "p", names(cs)))
cbind(df, cs)
#    retroid pitchcount p1 p2 p3   p4   p5   p6   p7
# 1 loftk001    BBBCCFB  B  B  B    C    C    F    B
# 2  vizq001        CCX  C  C  X <NA> <NA> <NA> <NA>

Another option is to use the new stri_list2matrix function from stringi

library(stringi)

ss <- strsplit(as.character(df$pitchcount), "")
cbind(df, stri_list2matrix(ss, byrow = TRUE, fill = ""))
#    retroid pitchcount 1 2 3 4 5 6 7
# 1 loftk001    BBBCCFB B B B C C F B
# 2  vizq001        CCX C C X        

And then you could just paste "p" onto the front of the new columns' names

Sign up to request clarification or add additional context in comments.

Comments

0

Another, perhaps a bit clearer:

df <- cbind(df, matrix(nrow=20)) # or however many columns you need

sapply(1:nrow(df), function(x) {
  pc <- df$pitchcount[x]
  y <- 
  df[x, 2 + seq_along(nchar(pc))] <<- strsplit(pc, split="")[[1]]
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.