Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

Replacing variable values using newly dated version of the variable [duplicate]

$
0
0

This question already has an answer here:

I am trying to replace update values for x, q, z using the recently available version of the variable indexed by date. In STATA, we can easily do it as a for loop (see sample code below). STATA

  • y refers to the date value of 20191125
local y 20191125

foreach v in x, q, z{
replace `v'=`v'`y' if !missing(`v'`y')
}

Data

+----+----+---+-----------+-----------+-----------+
| X  | Q  | Z | X20191125 | Q20191125 | Z20191125 |
+----+----+---+-----------+-----------+-----------+
| 1  | 2  | 3 |         6 |         8 |         0 |
| 1  | NA | 0 |         1 |         1 |         1 |
| NA | 0  | 1 |         5 |         4 |         2 |
+----+----+---+-----------+-----------+-----------+

Potential output:

+----+----+---+-----------+-----------+-----------+
| X  | Q  | Z | X20191125 | Q20191125 | Z20191125 |
+----+----+---+-----------+-----------+-----------+
| 1  | 2  | 3 |         6 |         8 |         0 |
| 1  |1 | 0 |         1 |         1 |         1 |
| 5| 0  | 1 |         5 |         4 |         2 |
+----+----+---+-----------+-----------+-----------+

I know how to replace NA values for one column from another column. How can I do the same using purrr dynamically? How can I tell R to replace values from a variable with the same name + date prefix? I have about 25 variables in my dataset that require this.

#Method 1: I can do it one variable at a time
df%<>%
mutate(x=ifelse(is.na(x)==T, x20191125, x),
       q=ifelse(is.na(x)==T, q20191125, q),
       z=ifelse(is.na(x)==T, z20191125, z,)

#Method 2: using mutate_at (but not sure how I can dynamically refer to the date indexed variable?).

df%<>%
mutate_at(vars(starts_with(x,q,z)), ifelse(.=ifelse(is.na(.)==T, x20191125, .))

Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>