Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

dataframe - Data Split in R based on Row Relationship Values

My Dataframe has the following structure:

Start Value Middle Value(s) Final Value Relationship
A B C lowers, lowers
A D, E C lowers, raises, raises
question from:https://stackoverflow.com/questions/65864003/data-split-in-r-based-on-row-relationship-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We could unite the columns and then split the column with separate_rows

library(dplyr)
library(tidyr)
df1 %>% 
  unite(StartValue, StartValue, MiddleValue, sep=", ", remove = FALSE) %>%
  unite(FinalValue, MiddleValue, FinalValue, sep=", ") %>% 
  separate_rows(c(StartValue, FinalValue, Relationship))

-output

# A tibble: 5 x 3
#  StartValue FinalValue Relationship
#  <chr>      <chr>      <chr>       
#1 A          B          lowers      
#2 B          C          lowers      
#3 A          D          lowers      
#4 D          E          raises      
#5 E          C          raises        

data

df1 <- structure(list(StartValue = c("A", "A"), MiddleValue = c("B", 
"D, E"), FinalValue = c("C", "C"), Relationship = c("lowers, lowers", 
"lowers, raises, raises")), class = "data.frame", row.names = c(NA, 
-2L))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...