Falves Falves - 3 years ago 51
R Question

R programm: How to extract the 4th element of a dataframe?

I have a simply question about R programm, but I really dont know how to solve, please, help me!

I have a dataframe with 280 observations of 480 variables and would like to save in a new dataframe, from the first row, the element that appears every three columns.

So, my dataframe is like:

X1 X2 X3 X4 X5 X6 X7 X8
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 06/03/2017 07/03/2017


I try to save the first row and do some loop, and thougth to take each 4th element, but I'm doing something wrong:

row1 <- as.list(plan [1, ])
i <- -3

for (i in plan) {
dates <- as.list (i)
}


Thank you, so much!

my output could be something like this:

06/03/2017
07/03/2017
08/03/2017
09/03/2017


(continue until finish all 480 variables)

Edited the question after some negative notes that I dont understand :/ Really sorry

Answer Source

Hope this helps!

df <- data.frame(x1=c(1,2),x2=c(1,2),x3=c(1,2),x4=c(444,555),
                 x5=c(1,2),x6=c(1,2),x7=c(1,2),x8=c(666,777))
names <- names(df)
idx <- c()
for (i in 1:(length(names)/4)) idx[i] <- 4*i
df[,names[idx]]

Don't forget to let us know in case it solved your problem :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download