Raphael
Raphael

Reputation: 29

Using the column name as a variable

I have a list of data.frames which consist of data in the fourth row. The column name in the fourth row is for each data.frame different:

[[1]]
# A tibble: 47 x 4
   PlateName                                Row Column  `xic-413.1---396.0`
   <chr>                                  <dbl>  <dbl>                <dbl>
 1 20210722                                   1      1                 975.
 2 20210722                                   1      1                1089.


[[2]]
# A tibble: 47 x 4
   PlateName                              Row Column  `xic-346.1---329.0`
   <chr>                                <dbl>  <dbl>                <dbl>
 1 20210722                                 1      1                8472.
 2 20210722                                 1      1                8683.

What I wanna do is get a new row with the data from the fourth row but with a general column name (lets say "readout") and a row with the column name for each row (lets name the column "mass") So my list should look like this:

[[1]]
# A tibble: 47 x 4
   PlateName                                Row Column              readout                  mass
   <chr>                                  <dbl>  <dbl>                <dbl>                 <dbl>
 1 20210722                                   1      1                 975.    `xic-413.1---396.0`
 2 20210722                                   1      1                1089.    `xic-413.1---396.0`


[[2]]
# A tibble: 47 x 4
   PlateName                              Row Column              readout                  mass
   <chr>                                <dbl>  <dbl>                <dbl>                 <dbl> 
 1 20210722                                 1      1                8472.    `xic-346.1---329.0`
 2 20210722                                 1      1                8683.    `xic-346.1---329.0`

How can I accomplish that?

Upvotes: 0

Views: 38

Answers (1)

stefan
stefan

Reputation: 123783

Making use of iris as example data you could so:

lapply(list(iris[1:2, ], iris[1:2, ]), function(x) {
  x[["mass"]] <- names(x)[[5]]
  names(x)[[5]] <- "readout"
  x
})
#> [[1]]
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width readout    mass
#> 1          5.1         3.5          1.4         0.2  setosa Species
#> 2          4.9         3.0          1.4         0.2  setosa Species
#> 
#> [[2]]
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width readout    mass
#> 1          5.1         3.5          1.4         0.2  setosa Species
#> 2          4.9         3.0          1.4         0.2  setosa Species

Upvotes: 3

Related Questions