I have the following list of named vectors:
lof <- list(PP1 = c(A = -0.96, R = 0.8, N = 0.82, D = 1, C = -0.55,
E = 0.94, Q = 0.78, G = -0.88, H = 0.67, I = -0.94, L = -0.9,
K = 0.6, M = -0.82, F = -0.85, P = -0.81, S = 0.41, T = 0.4,
W = 0.06, Y = 0.31, V = -1), PP2 = c(A = -0.76, R = 0.63, N = -0.57,
D = -0.89, C = -0.47, E = -0.54, Q = -0.3, G = -1, H = -0.11,
I = -0.05, L = 0.03, K = 0.1, M = 0.03, F = 0.48, P = -0.4, S = -0.82,
T = -0.64, W = 1, Y = 0.42, V = -0.43), PP3 = c(A = 0.31, R = 0.99,
N = 0.02, D = -1, C = 0.19, E = -0.99, Q = -0.38, G = 0.49, H = 0.37,
I = -0.18, L = -0.24, K = 1, M = -0.08, F = -0.58, P = -0.07,
S = 0.57, T = 0.37, W = -0.47, Y = -0.2, V = -0.14))
What I want to do is to convert it to tibble and keeping the name of the vector as a column in a tibble.
With this:
library(tidyverse)
as_tibble(lof)
I get this:
# A tibble: 20 × 3
PP1 PP2 PP3
<dbl> <dbl> <dbl>
1 -0.96 -0.76 0.31
2 0.8 0.63 0.99
.. etc ...
What I want to get is this:
PP1 PP2 PP3. residue
1 -0.96 -0.76 0.31 A
2 0.8 0.63 0.99 R
.. etc ...
How can I achieve that?
CodePudding user response:
It is straightforward to add a new column named "residue":
as_tibble(lof) %>%
mutate(residue = names(lof[[1]]))
# A tibble: 20 × 4
PP1 PP2 PP3 residue
<dbl> <dbl> <dbl> <chr>
1 -0.96 -0.76 0.31 A
2 0.8 0.63 0.99 R
3 0.82 -0.57 0.02 N
4 1 -0.89 -1 D
5 -0.55 -0.47 0.19 C
6 0.94 -0.54 -0.99 E
7 0.78 -0.3 -0.38 Q
8 -0.88 -1 0.49 G
9 0.67 -0.11 0.37 H
10 -0.94 -0.05 -0.18 I
11 -0.9 0.03 -0.24 L
12 0.6 0.1 1 K
13 -0.82 0.03 -0.08 M
14 -0.85 0.48 -0.58 F
15 -0.81 -0.4 -0.07 P
16 0.41 -0.82 0.57 S
17 0.4 -0.64 0.37 T
18 0.06 1 -0.47 W
19 0.31 0.42 -0.2 Y
20 -1 -0.43 -0.14 V
or
lof_new <- as_tibble(lof)
lof_new$residue <- names(lof[[1]])
CodePudding user response:
The other answer works however if your names are not in order in all of the list items or they are of different lengths, you could also use the below.
library(tidyverse)
lof %>%
map(~tibble(name = names(.x), value=.x)) %>%
bind_rows(.id = "ID") %>%
pivot_wider(names_from = ID, values_from = value, values_fill = NA)
# A tibble: 20 x 4
name PP1 PP2 PP3
<chr> <dbl> <dbl> <dbl>
1 A -0.96 -0.76 0.31
2 R 0.8 0.63 0.99
3 N 0.82 -0.57 0.02
4 D 1 -0.89 -1
5 C -0.55 -0.47 0.19
6 E 0.94 -0.54 -0.99
7 Q 0.78 -0.3 -0.38
8 G -0.88 -1 0.49
9 H 0.67 -0.11 0.37
10 I -0.94 -0.05 -0.18
11 L -0.9 0.03 -0.24
12 K 0.6 0.1 1
13 M -0.82 0.03 -0.08
14 F -0.85 0.48 -0.58
15 P -0.81 -0.4 -0.07
16 S 0.41 -0.82 0.57
17 T 0.4 -0.64 0.37
18 W 0.06 1 -0.47
19 Y 0.31 0.42 -0.2
20 V -1 -0.43 -0.14
CodePudding user response:
bind_cols(lof, residue=names(lof$PP1))