r - Subtract a row of prices in one dataframe from columns in another -
i have dataframe 163 columns unique names, (x1, x2, x3, x4 ....) each of these columns has series of returns (0.248, -0.00384, etc).
**df1** x1 x2 x3 x4 ..... 0.248 -0.00384 0.0394 0.0053 .....
in dataframe have 1 column list of same unique names (x1, x2, x3, x4 ...) , list of numbers (0.005, .001, etc).
**df2** x1 0.005 x2 0.001 x3 0.005 x4 0.0005 ...
my ultimate goal homecoming dataframe 163 columns (x1, x2, etc) each columns net returns (so x1 column original returns subtracted 0.005, x2 column original returns subtracted 0.001, etc).
so far tried sorting sec dataframe, transposing , using unlist vector of numbers, subtract each column (but cant figure out how subtract each column). help figuring out how helpful. list of unique names in sec dataframe same first dataframe, sorted alphabetically, doesnt need matched (both sorted line up).
in case, colnames of df1
, rownames of df2
not in same order, can utilize match
df1-df2[match(colnames(df1), rownames(df2)),1][col(df1)]
should work if either or both datasets not in same order. example
set.seed(65) df1n <- df1[,sample(colnames(df1))] df1n-df2[match(colnames(df1n), rownames(df2)),1][col(df1n)]
if in order
df1-df2[,1][col(df1)]
data set.seed(24) df1 <- as.data.frame(matrix(rnorm(40*10), ncol=10, dimnames=list(null, paste0("x", 1:10))) ) set.seed(42) df2 <- data.frame(col1=rnorm(10, 0.01)) row.names(df2) <- sample(paste0("x",1:10))
r sorting data.frame subtraction
No comments:
Post a Comment