【问题标题】:How do i replace the fourth row of values in a dataframe with a corresponding vector in R?如何用 R 中的相应向量替换数据框中的第四行值?
【发布时间】:2020-10-08 15:01:57
【问题描述】:

我有一组价值观

 col1|col2|col3|col4
    5   10   15   20
    2    4    6    8
    3    6    9   12
    4    3    7   15

我想用向量替换第 4 行

 c(4,8,12,16)

我想在第 4 列中插入向量并替换原始值。我试过这个脚本。

df[[4]]<- vector_name

我期待结果

  col1|col2|col3|col4
    5   10   15   20
    2    4    6    8
    3    6    9   12
    4    8   12   16

【问题讨论】:

标签: r dataframe vector


【解决方案1】:

我们可以使用replace

replace(df1, cbind(nrow(df1), seq_along(df1)), v1)

数据

df1 <- structure(list(col1 = c(5L, 2L, 3L, 4L), col2 = c(10L, 4L, 6L, 
3L), col3 = c(15L, 6L, 9L, 7L), col4 = c(20L, 8L, 12L, 15L)),
class = "data.frame", row.names = c(NA, 
-4L))

v1 <- c(4, 8, 12, 16)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2021-09-05
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多