简体   繁体   English

如果一行符合条件,请粘贴 R

[英]If a row matches a criteria do paste in R

Let's imagine you have a dataframe with two columns ID and POSITION .假设您有一个 dataframe 具有两列IDPOSITION I want to paste some text depending on the ID value.我想根据 ID 值粘贴一些文本。

I want to paste the ID value with GK0000 (when ID>10) or GK00000 (when ID<10) along with .2: , POSITION value, .. and the following POSITION value (POSITION+1)我想粘贴带有GK0000 (当 ID>10 时)或GK00000 (当 ID<10 时)的 ID 值以及.2:POSITION值、 ..以及以下POSITION(POSITION+1)

For example if ID = 1 and POSITION = 10 , the result would be GK000001.2:10..11 and if ID = 10 and POSITION = 10 , the result would be GK000010.2:10..11例如,如果ID = 1POSITION = 10 ,则结果将为GK000001.2:10..11 ,如果ID = 10POSITION = 10 ,则结果将为GK000010.0.10.2:

In Excel I can do this being A as ID and B as POSITION using =IF(A2<10,CONCATENATE("GK00000",A2,".2:",B2,"..",B2+1),CONCATENATE("GK0000",A2,".2:",B2,"..",B2+1)) but I want to add it to my R script line.A中,我POSITION使用 =IF(A2<10,CONCATENATE(" ID ",A2,".2:", B =IF(A2<10,CONCATENATE("GK00000",A2,".2:",B2,"..",B2+1),CONCATENATE("GK0000",A2,".2:",B2,"..",B2+1))但我想将它添加到我的 R 脚本行中。

I give you a short example of my input data just ilustrative我给你一个简短的例子来说明我的输入数据

ID <- c(1,5,9,10,12)
POSITION <- c(10,50,90,100,120)
df <- cbind(ID,POSITION)

and the result I'm expecting is我期待的结果是

CONCAT <- c("GK000001.2:10..11","GK000005.2:50..51","GK000009.2:90..91",
            "GK000010.2:100..101","GK000012.2:120..121")
dfResult <- cbind(ID,POSITION,CONCAT)

I believe the question asks for a string format given two arguments, A and B and a number of digits.我相信这个问题要求给出两个 arguments、 AB以及多个数字的字符串格式。

concat <- function(A, B, digits = 6){
  fmt <- paste0("%0", digits, "d")
  fmt <- paste0("GK", fmt, ".2:%d..%d")
  sprintf(fmt, A, B, B + 1)
}

concat(df[, 'ID'], df[, 'POSITION'], 6)
# [1] "GK000001.2:10..11"   "GK000002.2:20..21"   "GK000003.2:30..31"  
# [4] "GK000004.2:40..41"   "GK000005.2:50..51"   "GK000006.2:60..61"  
# [7] "GK000007.2:70..71"   "GK000008.2:80..81"   "GK000009.2:90..91"  
#[10] "GK000010.2:100..101" "GK000011.2:110..111" "GK000012.2:120..121"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM