用向量替换data.table的一部分

时间:2019-05-21 22:40:26

标签: r replace data.table

我有一个可以创建的数据表

<!DOCTYPE html>
<html>
<body>

<div> <a id="myVideoTag"> </a> </div>

<script>

//# generate random number
var number = Math.floor(Math.random() * 3) + 1;
var mySrc = "/images/media/Video-" + number + ".mp4";

//# create video element to append into above <a> tag           
tmpElement = document.createElement( "video");
tmpElement.setAttribute("controls", "true" );
tmpElement.setAttribute("width", "800");
tmpElement.setAttribute("src", mySrc);

//# append the dynamically created element...
var container = document.getElementById("myVideoTag");
container.appendChild(tmpElement);

</script>

</body>
</html>

我要替换第1行和第top_m_dt = data.table(future_fip = c(102, 104, 503), model = c("model_1", "model_2", "model_3"), time_period = c("F1", "F2", "F3"), emission = c("emission_1", "emission_2", "emission_3"), top_1_fip = c(666, 666, 666), top_2_fip = c(666, 666, 666), top_3_fip = c(666, 666, 666)) top_1_fiptop_2_fip列 带有一组值,假设top_3_fip

以下任何一项均不起作用:

c(10, 20, 30)

OR

top_m_dt[1, c("top_1_fip", "top_2_fip", "top_3_fip")] <- 
    as.numeric(analog_dat_F1$analog_NNs_county[1:3])`

OR

top_m_dt[1, 5:7 ] <- list(analog_dat_F1$analog_NNs_county[1:3])[[1]]

它们都在所有三个位置替换top_m_dt[1, (c("top_1_fip", "top_2_fip", "top_3_fip")):= analog_dat_F1$analog_NNs_county[1:3]] ` 。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

data.table的语法略有不同,并且并非所有适用于数据框的内容都适用于data.table。在这种情况下,您可以使用as.list

替换特定行和列中的值
library(data.table)
top_m_dt[1, c("top_1_fip", "top_2_fip", "top_3_fip") := as.list(c(10, 20, 30))]

top_m_dt
#   future_fip   model time_period emission top_1_fip top_2_fip top_3_fip
#1: target_fip model_n          F1 emission        10        20        30
#2: target_fip model_n          F2 emission       666       666       666
#3: target_fip model_n          F3 emission       666       666       666