英文:
Creating a data frame in R with ifelse omits rows (vector values)
问题
Creating a dataframe out of a vector works well, like this:
VEC <- c("Vienna", "Tokyo")
TEST <- data.frame(
"city" = VEC
)
# TEST now has 1 column ("city") with two rows ("Vienna", "Tokyo")
However, using ifelse()
leads to the omission of all rows (vector values) other than the first one:
TEST <- data.frame(
"city" = ifelse(is.null(VEC), NA, VEC)
)
# TEST now has 1 column ("city") with ONLY ONE ROW ("Vienna")
Is there any other way to check whether a vector is null while retaining the whole vector for the dataframe?
英文:
Creating a dataframe out of a vector works well, like this:
VEC <- c("Vienna", "Tokyo")
TEST <- data.frame(
"city" = VEC
)
# TEST now has 1 column ("city") with two rows ("Vienna", "Tokyo")
However, using ifelse()
leads to the omission of all rows (vector values) other than the first one:
TEST <- data.frame(
"city" = ifelse(is.null(VEC), NA, VEC)
)
# TEST now has 1 column ("city") with ONLY ONE ROW ("Vienna")
Is there any other way to check whether a vector is null while retaining the whole vector for the dataframe?
答案1
得分: 1
你可以尝试以下两种方式之一:
ifelse(is.null(VEC), NA, list(VEC))[[1]]
或者
if (is.null(VEC)) NA else VEC
英文:
You can try either
ifelse(is.null(VEC), NA, list(VEC))[[1]]
or
if (is.null(VEC)) NA else VEC
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论