Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

r loop only returns one dataframe

I have a data structure like so:

daynum year1 year2 year3
1jan 1 3 4
2jan 2 4 6

I want to coalesce the column titles to the day numbers into a new column, then stack the first 70 rows of each column into 1 new column.

daynum = c("day1", "day2", "day3", "day4")
year1 = c(1,2,3,4)
year2 = c(5,6,7,8)
year3 = c(7,8,9,10)

df <- data.frame(daynum, year1, year2, year3)
print(df)

  #create output data outside of loop
summerdata = data.frame()

for (i in names(df[,-1])){
  yeardate = data.frame(paste(i, df$daynum, sep="-"))
  sdata = data.frame(df[[i]])
  sur = sdata[1:70,]
  sy = yeardate[1:70,]
  endsummers = cbind(sy,sur)
  summerdata = rbind(summerdata,endsummers)
}
colnames(endsummers)=c("yeardate","summertemp")
print(endsummers)  

all that returns in the first year1, and it’s storing the numbers as text.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

output should look like this:

      yeardate       summertemp
 [1,] "year1-day1"  85      
 [2,] "year1-day2"  87     
 [3,] "year1-day3"  79  

>Solution :

library(tidyverse)
df %>%
  pivot_longer(-daynum) %>%
  group_by(name) %>% slice(1:70) %>% ungroup() %>%  # only first 70 rows per year
  unite("daynum", 2:1, sep = "-") %>%
  arrange(daynum)

Result

# A tibble: 12 × 2
   daynum     value
   <chr>      <dbl>
 1 year1-day1     1
 2 year1-day2     2
 3 year1-day3     3
 4 year1-day4     4
 5 year2-day1     5
 6 year2-day2     6
 7 year2-day3     7
 8 year2-day4     8
 9 year3-day1     7
10 year3-day2     8
11 year3-day3     9
12 year3-day4    10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading