Home > Back-end >  Populate R dataframe with a for lopp
Populate R dataframe with a for lopp

Time:07-18

The output I have now looks like

   [2] "DOYLESTOWN HOSPITAL | PA | 10.4"                                              
   [3] "GLENDALE ADVENTIST MEDICAL CENTER | CA | 10.5"                                
   [4] "AVERA HEART HOSPITAL OF SOUTH DAKOTA LLC | SD | 10.5"                         
   [5] "WATERBURY HOSPITAL | CT | 10.6"                                               
   [6] "MAIN LINE HOSPITAL LANKENAU | PA | 10.7" 

I am using this code to generate that list

for (x in df){
  paste(df$name,df$state, df$outcome, sep = " | ")
}

Now I'd like to create a dataframe instead and populate it with this data

Expected output

                      hospital state rank
   D W MCMILLAN MEMORIAL HOSPITAL AL   10
ARKANSAS METHODIST MEDICAL CENTER AR   14

class(df) [1]

"data.frame"

CodePudding user response:

We can use:

mytext <- c("DOYLESTOWN HOSPITAL | PA | 10.4","GLENDALE ADVENTIST MEDICAL CENTER | CA | 10.5")
splitted <- strsplit(mytext, split="\\|")
hospital <- sapply(splitted, function(x) x[[1]])
state <- sapply(splitted, function(x) x[[2]])
rank <- sapply(splitted, function(x) x[[3]])

> result
                            hospital state  rank
1               DOYLESTOWN HOSPITAL    PA   10.4
2 GLENDALE ADVENTIST MEDICAL CENTER    CA   10.5

However, I don't really see the point if you already have the data available in df. Of course if you were just after the syntax, it makes sense.

Please do make your data reproducible next time.

CodePudding user response:

In base R, we may use read.csv/read.table if we specify the delimiter correctly

read.csv(text = gsub("\\s \\|\\s ", ",", str1), 
  header = FALSE, col.names = c("hospital", "state", "rank"))
                           hospital state rank
1               DOYLESTOWN HOSPITAL    PA 10.4
2 GLENDALE ADVENTIST MEDICAL CENTER    CA 10.5

data

str1 <- c("DOYLESTOWN HOSPITAL | PA | 10.4", 
"GLENDALE ADVENTIST MEDICAL CENTER | CA | 10.5"
)
  • Related