在R中使用ifelse创建数据框会省略行(向量值)。

huangapple go评论99阅读模式
英文:

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 &lt;- c(&quot;Vienna&quot;, &quot;Tokyo&quot;)
TEST &lt;- data.frame(
   &quot;city&quot; = VEC
)
# TEST now has 1 column (&quot;city&quot;) with two rows (&quot;Vienna&quot;, &quot;Tokyo&quot;)

However, using ifelse() leads to the omission of all rows (vector values) other than the first one:

TEST &lt;- data.frame(
   &quot;city&quot; = ifelse(is.null(VEC), NA, VEC)
)
# TEST now has 1 column (&quot;city&quot;) with ONLY ONE ROW (&quot;Vienna&quot;)

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

huangapple
  • 本文由 发表于 2023年8月10日 15:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定