R - 逐行替换选定列中的值 [英] R - Replace values starting in selected column by row

查看:38
本文介绍了R - 逐行替换选定列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想逐行用零替换特定月份之后的月度值.我尝试调整 从不同列开始替换数据帧中的 NA 值 没有成功.给定数据:

I want to replace with zero the monthly values that are after a specific month by row. I have tried adapting Replace NA values in dataframe starting in varying columns without success. Given data:

df <- structure(list(Mth1 = c(1L, 3L, 4L, 1L, 2L), 
                      Mth2 = c(2L, 3L, 2L, 2L, 2L),
                      Mth3 = c(1L, 2L, 1L, 2L, 3L), 
                      Mth4 = c(3L, 1L, 3L, 4L, 2L),
                      ZeroMth = c(1L, 3L, 2L, 4L, 3L)),
                 .Names = c("Mth1", "Mth2", "Mth3", "Mth4", "ZeroMth"), class = "data.frame", 
                 row.names = c("1", "2", "3", "4", "5"))


> df
  Mth1 Mth2 Mth3 Mth4 ZeroMth
1    1    2    1    3       1
2    3    3    2    1       3
3    4    2    1    3       2
4    1    2    2    4       4
5    2    2    3    2       3

我想使用 ZeroMth 列中的值来指定替换开始的月份.所需的输出是:

I would like to use the values in the ZeroMth column to specify the month where the replacements start. The desired output is:

> df1
  Mth1 Mth2 Mth3 Mth4
1    0    0    0    0
2    3    3    0    0 
3    4    0    0    0
4    1    2    2    0
5    2    2    0    0

推荐答案

在每一行使用 apply (MARGIN = 1) 和 replace最后一列中指定的索引后的值为零

Use apply on each row (MARGIN = 1) and replace the values after the index specified in the last column to be zero

t(apply(X = df, MARGIN = 1, function(x)
    replace(x = x, list = x[NCOL(df)]:(NCOL(df)-1), values = 0)))
#  Mth1 Mth2 Mth3 Mth4 ZeroMth
#1    0    0    0    0       1
#2    3    3    0    0       3
#3    4    0    0    0       2
#4    1    2    2    0       4
#5    2    2    0    0       3

这篇关于R - 逐行替换选定列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆