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L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 2L, 3L, 3L), levels = c("ddd", "eee", "fff"
), class = c("ordered", "factor"))
dftest1 <-
structure(c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1L, NA, NA, NA, 1L, NA, NA, NA, 2L, NA, NA, NA,
1L, NA, NA, NA, NA, NA, NA, 1L, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1L, NA, 2L), levels = c("AAA", "BBB"
), class = "factor")
dftest2 <-
structure(c(NA, NA, NA, NA, NA, NA, NA, 1L, NA, NA, NA, 1L, NA,
1L, NA, 1L, NA, NA, NA, NA, NA, NA, NA, NA, 1L, NA, NA, NA, NA,
NA, NA, 1L, 1L, NA, 1L, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1L,
NA, NA, NA, NA, 1L, NA, NA, NA, 1L, NA, 1L, NA, 1L, NA, NA, NA,
1L, NA, NA, NA, NA, NA, NA, 1L, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1L, 1L, 1L), levels = "CCC", class = "factor")
I want to put df1
, df2
and df3
(in my case factors) together as placeholders vars2use
, so to speak.
var2use <- c(var1, var2, var3)
This placeholder should then be combined with other factors (dftest1
, dftest2
) into a data set.
This implementation works as expected:
df <- data.frame(dftest1, dftest2, df1, df2, df3)
I was hoping that it could also be implemented in this form:
df <- data.frame(dftest1, dftest2, var2use)
But I get an error:
Error in data.frame(dftest1, dftest2, var2use):
arguments imply differing number of rows: 82, 3
The background is that I would like to work with placeholders of this type in different places. Does anyone have an idea how to solve this?
CodePudding user response:
The more direct way to do this is to just put your values in to a separte data.frame and then cbind()
the values when you need them. For example
vars2use <- data.frame(df1, df2, df3)
df <- cbind(data.frame(dftest1, dftest2), vars2use)
# df <- data.frame(dftest1, dftest2) |> cbind(vars2use) # alternative syntax
If for some reason those names really do need to be a character vector, you can use mget()
to get the values before using cbind
varnames <- c("df1", "df2", "df3")
df <- cbind(data.frame(dftest1, dftest2), mget(varnames))
CodePudding user response:
Assuming that dftest1
and dftest2
are both dataframes of equal size to (var1-var3) then both work completely fine per the code below.
I think the issue in your example is you're calling df1-df3, however your objects are called var1, var2, and var3
However, since you haven't shown what error is thrown as your example then I'm not sure how we're supposed to derive the correct conclusion.
var1 <- "df1"
var2 <- "df2"
var3 <- "df3"
var2use <- c(var1, var2, var3)
dftest1 <- "df4"
dftest2 <- "df5"
df <- data.frame(dftest1, dftest2, var1, var2, var3)
df <- data.frame(dftest1, dftest2, var2use)