0

My data looks like

a  
a >> b  
d >> c >> e 

(unknown times ">>") can be present in a row
And I need them in several columns depending on occurrences of ">>"
I tried strsplit, which converts the column in a list and when I tried to unlist it, it repeats the values like

X1 X2 X3   
a  a  a  
a  b  a  
d  c  e

Is there any Base R solution to get

X1 X2 X3  
a  
a  b  
d  c  e 

And so on? I can only use Base R!!

2
  • Please share your sample input with dput so we can see the structure we're working with. dput(your_sample). Commented Feb 17, 2021 at 16:04
  • @Pushkar, if the answer below solves your problem do consider accepting it or voting on it. If it doesn't, consider clarifying what is still unresolved. Thanks. Commented Feb 17, 2021 at 22:29

1 Answer 1

1

Assuming your input is a character vector as below, try this:

x = c("a"  ,
"a >> b"  ,
"d >> c >> e")


s = lapply(strsplit(x, split = ">>"), trimws)
s = t(sapply(s, function(x) {length(x) <- max(lengths(s)); x}))
s
#      [,1] [,2] [,3]
# [1,] "a"  NA   NA  
# [2,] "a"  "b"  NA  
# [3,] "d"  "c"  "e"
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much!
Congrats on passing 100k! Have you gotten your swag yet? I wonder whether there's any advantage to t(s/v-apply) since the desired output is a matrix anyway.
@A5C1D2H2I1M1N2O1R2T1 Thanks! No, nothing yet - I did get a congratulatory email but no mention of swag. I wonder if the threshold was raised.
Good call on the t(sapply()) - saves a step.
@GregorThomas, strange. There was a post somewhat recently in Meta SE that swag is back.

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.