![](/img/trans.png)
[英]Creating a Vector from a dataframe that discriminates values based on another column in r
[英]Creating a column in a dataframe with values from another dataframe in R
我有一個具有以下結構的數據框:
V1 V2 V3 V4 V5 V6 V7 V8
A B A B B A B B
它只有一行,每列有一個字母。 我想將這些字母兩個兩個地插入另一個數據框中,如下所示:
V1 V2 V3
X AB F
Y AB G
Z BA H
W BB I
我應該如何進行? 也許將第一個數據幀變成向量?
提前致謝!
我不知道V1
和V3
是從哪里來的,但是下面的代碼可以幫助您生成V2
do.call(rbind,
Map(function(x) do.call(paste0,x),
split.default(df1,ceiling(seq_along(df1)/2)))
)
這使
[,1]
1 "AB"
2 "AB"
3 "BA"
4 "BB"
數據
> dput(df1)
structure(list(V1 = "A", V2 = "B", V3 = "A", V4 = "B", V5 = "B",
V6 = "A", V7 = "B", V8 = "B"), class = "data.frame", row.names = c(NA,
-1L))
這是一種更冗長的方法。
xy <- structure(list(V1 = "A", V2 = "B", V3 = "A", V4 = "B", V5 = "B",
V6 = "A", V7 = "B", V8 = "B"), class = "data.frame", row.names = c(NA,
-1L))
xy <- unlist(xy) # split doesn't work on data.frames
# Make sure that length of xy is divisible by 2.
stopifnot((length(xy) %% 2) == 0)
tosplit <- rep(1:(length(xy) / 2), each = 2)
tosplit <- factor(tosplit)
xy <- split(xy, f = tosplit)
xy <- lapply(xy, FUN = paste, collapse = "")
xy <- unlist(xy)
xy
1 2 3 4
"AB" "AB" "BA" "BB"
這可以很容易地操作到您選擇的 data.frame 中。
我們也可以轉換成兩列的matrix
,然后進行paste
do.call(paste0, as.data.frame(matrix(unlist(df1), ncol = 2, byrow = TRUE)))
#[1] "AB" "AB" "BA" "BB"
df1 <- structure(list(V1 = "A", V2 = "B", V3 = "A", V4 = "B", V5 = "B",
V6 = "A", V7 = "B", V8 = "B"), class = "data.frame", row.names = c(NA,
-1L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.