简体   繁体   中英

Extracting Data from Vector Elements in R

I am trying to write an R script to parse ordered pairs of numbers from csv file cells. Here are the first few rows of the CSV file:

Test1,   Test2,                     Test3
Label1,  [(1, 2), (5, 6), (9, 10)], High
Label2,  [(5, 9), (6, 10)],         Low
Label3,  [(0, 5)],                  High

Note that the second column is a list of tuples resulting from running a Python script. I wrote an R script to read the csv file as a table using read.csv, and then create vectors from each column. I then want it to read each ordered pair (tuple) from each vector element/cell from Column 2 and use them for the beginning and ending x-values for plotting rectangles. But I cannot parse the individual ordered pairs (tuples) from the vector element. No matter what I do, R still considers the vector element as one object, never an array or a list.

Here is the R code:

table1 <- read.csv("data.csv",header=TRUE,sep=",")
val1 <- paste(table1[,1])
val2 <- paste(table1[,2]) # First data row is [(1, 2), (5, 6), (9, 10)]
val3 <- paste(table1[,3])
nrows = length(val1)
for (i in 1:nrows) {
    rects <- val2[i]  # rects <- [(1, 2), (5, 6), (9, 10)]
    nval <- length(rects)  # Want nval to be 3
    if (nval > 0) {
        for (j in 1:nval) {
            bounds <- rects[j]  # Want bounds to be (1, 2), then (5, 6), then (9, 10)
            start <- bounds[1]  # Want start to be 1, 5, and then 9
            stop <- bounds[2]  # Want stop to be 2, 6, and then 10
            w <- stop - start # w should be 1
            vpp <- start + w/2 # vpp will be 1.5, 5.5, and then 9.5
            pushViewport(vp)
            grid.rect(x=0.5, y=0.5, width=w, height=0.5, gp=gpar(fill="violet"))
            upViewport()
         }
    }
}

I am not sure I 100% understand what you want the final output to be, but here's a way to end up with a data frame like this, with the beginning and ending x values separated:

   Test1                 Test3 X1 X2
1 Label1                  High  1  2
2 Label1                  High  5  6
3 Label1                  High  9 10
4 Label2                   Low  5  9
5 Label2                   Low  6 10
6 Label3                  High  0  5

I created your data frame but had to manually substitute semicolons in the pasted text.

df <- read.table(text = "Test1;   Test2;                     Test3
Label1;  [(1, 2), (5, 6), (9, 10)]; High
Label2;  [(5, 9), (6, 10)];         Low
Label3;  [(0, 5)];                 High", sep = ";", header = TRUE, stringsAsFactors = FALSE)

First split on "), " which should messily split each list of points. Then split each tuple into two columns and remove all the extra parentheses etc.

splits <- strsplit(as.character(df$Test2), "), ")

# split up list of tuples
df2 <- data.frame(Test1 = rep(df$Test1, lapply(splits, length)), 
           Test3 = rep(df$Test3, lapply(splits, length)),
           Test2 = unlist(splits), stringsAsFactors = FALSE)

# split tuples into two columns
df3 <- cbind(df2[, c("Test1", "Test3")], 
             data.frame(do.call("rbind", strsplit(df2$Test2, ",", fixed = TRUE))))

# remove parens etc. and convert to numeric
df3$X1 <- as.numeric(gsub("[^[:digit:]]", "", df3$X1))
df3$X2 <- as.numeric(gsub("[^[:digit:]]", "", df3$X2))

This creates the data frame shown above and will allow you to plot rectangles doing something like the following (with random y values added to the data frame):

library('dplyr')
library('ggplot2')
set.seed(10)
df4 <- df3 %>%
  do(mutate(., ymin = sample(10, nrow(.)))) %>% # random y values for plotting
  mutate(ymax = ymin + 1)

ggplot(df4, aes(xmin = X1, xmax = X2, ymin = ymin, ymax = ymax)) +
  geom_rect()

This will look like: 情节

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM