Mohammad Osman Mohammad Osman - 1 month ago 9
R Question

Splitting a column ( column A with numbers) into sub columns with columns names as

Let's say I have a table as shown below.

Temp_C Source
1 16.73000 20090510
2 16.73750 20090510
3 16.64000 20090511
4 16.38667 20090511
5 16.25625 20090511


I want divide this table into two columns with column names as 20090510 and 20090511. I do not need the name 'Tem_c' and Source as colnames. My product should look like:

20090510
1 16.73000
2 16.73750


and

20090511
1 16.64000
2 16.38667
3 16.25625


I really appreciate your insight.

Answer

I deleted my original answer as it was poor. Sorry for the confusion. I created your data here as a dataframe. In the future, it is nice when you ask questions to provide the first 3 lines of code below.

Temp_C<-c(16.73000,16.73750,16.64000,16.38667,16.25625)
Source<-c("20090510","20090510","20090511","20090511","20090511")
df<-data.frame(cbind(Temp_C,Source))
df
    Temp_C   Source
1    16.73 20090510
2  16.7375 20090510
3    16.64 20090511
4 16.38667 20090511
5 16.25625 20090511

Next, I used split() to parse out your data in the way you requested, but the names of the first variable are not the value of Source yet as you requested.

mylist<-split(df,f=Source) ## split your data frame by Source)
mylist
$`20090510`
   Temp_C   Source
1   16.73 20090510
2 16.7375 20090510

$`20090511`
    Temp_C   Source
3    16.64 20090511
4 16.38667 20090511
5 16.25625 20090511

I then used a little loop to rename the first column of each list item equal to the value in Source. I also reas

for (i in 1:length(mylist)){
  names(mylist[[i]])[1]  <- as.character(mylist[[i]][1,2])
  rownames(mylist[[i]])<-NULL
  }
mylist
$`20090510`
  20090510   Source
1    16.73 20090510
2  16.7375 20090510

$`20090511`
  20090511   Source
1    16.64 20090511
2 16.38667 20090511
3 16.25625 20090511

This list now contains dataframes where the first variable is what you were wanting. There are probably better ways of doing this, but this is what I came up with.

Comments