有没有一种方法可以编辑此功能以将数字添加到同一列? [英] Is there a way to edit this function to add numbers to the same column?

查看:84
本文介绍了有没有一种方法可以编辑此功能以将数字添加到同一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此功能,能够将整数添加到现有数据框.它使用我的整数并将它们作为一列转置到数据帧中.当我添加一列较短的值时,行将自动分配为0.当我添加另一列较长的列时,所有现有的较短长度的列都将0设为与最长列相同的长度.例如...

I have this function that is able to add integers to an existing dataframe. It takes my integers and transposes them as a column into the dataframe. When I add a column of shorter value, the rows will automatically be assigned as 0. When I add another column of longer length, all the existing columns of shorter length add 0s to be the same length as the longest column. For example...

功能

add_peaks <- function(df, vec, colname) {
  colname <- title
  new_row <- max(nrow(df), length(vec))
  new_df <- df[1:new_row, ,drop = FALSE]
  new_df[colname] <- c(vec, rep(NA, new_row - length(vec)))
  new_df[is.na(new_df)] <- 0
  rownames(new_df) <- NULL
  new_df
}

现有数据框

Apeaks
1
6
5

整数

Bpeaks = 2 1 6 12 10 5 8
Cpeaks = 2 1
Dpeaks = 4 1 0 9 20 4 18 11 9 6

更新的数据框

Apeaks Bpeaks Cpeaks Dpeaks
1      2      2      4
6      1      1      1
5      6      0      0
0      12     0      9
0      10     0      20
0      5      0      4
0      8      0      18
0      0      0      11
0      0      0      9
0      0      0      6

有没有一种方法可以编辑该功能,以将相同名称的列(例如"Dpeaks")添加到"Dpeaks"列表中.其余长度较短的列加0时已经存在的列?例如...

Dpeaks = 2 1 4

Apeaks Bpeaks Cpeaks Dpeaks
1      2      2      4
6      1      1      1
5      6      0      0
0      12     0      9
0      10     0      20
0      5      0      4
0      8      0      18
0      0      0      11
0      0      0      9
0      0      0      6
0      0      0      2
0      0      0      1
0      0      0      4

谢谢您的帮助!

推荐答案

如果列已存在,则可以附加向量:

You can append the vector if the column is already existing :

add_peaks <- function(df, vec, colname) {
   if(colname %in% names(df)) vec <- c(df[[colname]], vec)
   new_row <- max(nrow(df), length(vec))
   new_df <- df[1:new_row, ,drop = FALSE]
   new_df[colname] <- c(vec, rep(NA, new_row - length(vec)))
   new_df[is.na(new_df)] <- 0
   rownames(new_df) <- NULL
   new_df
}

您可以对其进行测试:

Dpeaks = c(4, 1, 0, 9, 20, 4, 18, 11, 9, 6)
df <- add_peaks(df, Dpeaks, "Dpeaks")
df
#   Apeaks Dpeaks
#1       1      4
#2       6      1
#3       5      0
#4       0      9
#5       0     20
#6       0      4
#7       0     18
#8       0     11
#9       0      9
#10      0      6

Dpeaks = c(2, 1, 4)
df <- add_peaks(df, Dpeaks, "Dpeaks")
df

#  Apeaks Dpeaks
#1       1      4
#2       6      1
#3       5      0
#4       0      9
#5       0     20
#6       0      4
#7       0     18
#8       0     11
#9       0      9
#10      0      6
#11      0      2
#12      0      1
#13      0      4

这篇关于有没有一种方法可以编辑此功能以将数字添加到同一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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