squishy squishy - 1 month ago 16
R Question

Create new table based on characters

I have two questions.

1) I have a dataset (df) where the last column, which begins with "09", is on every other row. Like so:

a <- c("01+0135.","09-6999","01+0135.","09-6999")
b <- c("02+2015.", "", "02+2015.", "")
c <- c("03+0349.","", "03+0349.", "")
d <- c("04+0537.","","04+0542.","")
e <- c("05+170.1","","05+170.1","")
f <- c("06+0.033","","06+0.384","")
g <- c("07+0.001","","07+0.395","")
h <- c("08+0.000","","08+0.000","")
df <- data.frame(a,b,c,d,e,f,g,h)

> df

1 01+0135. 02+2015. 03+0349. 04+0537. 05+170.1 06+0.033 07+0.001 08+0.000
2 09-6999
3 01+0135. 02+2015. 03+0349. 04+0542. 05+170.1 06+0.384 07+0.395 08+0.000
4 09-6999


Is there a simple way to get every other row (perhaps using regex) to appear in a ninth column?

2) How do I remove the first three characters of each column (i.e. 06+) and the period at the end of each column for columns beginning with 01, 02, 03, and 04?

Answer

For the first issue, you can split and recombine:

df1 <- df[(1:nrow(df))%%2==1,]
df2 <- df[(1:nrow(df))%%2==0,]
df1$i <- df2$a

df1
#          a        b        c        d        e        f        g        h       i
# 1 01+0135. 02+2015. 03+0349. 04+0537. 05+170.1 06+0.033 07+0.001 08+0.000 09-6999
# 3 01+0135. 02+2015. 03+0349. 04+0542. 05+170.1 06+0.384 07+0.395 08+0.000 09-6999

For the second issue, the simplest way might be to use substr() (but that's assuming that you really only want characters 4 through 7 of each, otherwise we'll want to do something with regular expressions):

for(i in 1:4) df1[,i] <- substr(df1[,i],4,7)

df1
#      a    b    c    d        e        f        g        h       i
# 1 0135 2015 0349 0537 05+170.1 06+0.033 07+0.001 08+0.000 09-6999
# 3 0135 2015 0349 0542 05+170.1 06+0.384 07+0.395 08+0.000 09-6999