为什么 apply(x, 1, paste0(collapse="") 在正值之间留下空白? [英] Why does apply(x, 1, paste0(collapse="") leave white space between positive values?

查看:29
本文介绍了为什么 apply(x, 1, paste0(collapse="") 在正值之间留下空白?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在这个例子中跨列应用时,我得到了一个空格用于正值,但不是用于负值?为什么是这样?不应该 paste0 删除元素之间的空格吗?这个问题背后的背景是我试图为 googlemaps 方向 api 形成端点.

When I apply across columns in this example I get a white space for positive valued numbers but not for negative values? Why is this? Shouldn't paste0 remove whitespace between elements? The context behind this problem is that I am trying to form endpoints for the googlemaps directions api.

library(dplyr)
stop_latlon <- data.frame(lat = paste0("via:", rnorm(10)), lon = rnorm(10))

stop_latlon %>% 
  apply(1, function(x) paste0(x, collapse = "%7")) 

我认为这与在具有不同数据类型的数据帧上运行应用有关(lat 是字符,lon 是数字)

edit: I think that it has something to do with running apply on a dataframe with different data types (lat is a character and lon is a numeric)

推荐答案

为什么会出现空格?

paste0 不会添加空格 - 也不会删除它.您可以通过在您的矢量上调用 paste0 来测试这一点.

Why does the white space show up?

paste0 doesn't add white space - nor does it remove it. You can test this by just calling paste0 on your vector.

apply 在矩阵和数组上运行,而不是数据帧.当您将数据框传递给 apply 时,它会被强制转换为矩阵.当然,关于矩阵的主要事情是所有元素必须是相同的类型.由于字符串或因子通常不能被强制转换为数字,因此您的数字被强制转换为字符串或因子以匹配第一列.如果您检查 as.matrix.data.frame,您会看到 format 用于此转换,并且 ?format 显示默认值trim = FALSE 表示

apply runs on matrices and arrays, not data frames. When you pass a data frame to apply, it is coerced to a matrix. The main thing about a matrix, of course, is that all elements must be the same type. Since strings or factors can't generally be coerced to numerics, your numeric is coerced to a string or factor to match the first column. If you examine as.matrix.data.frame, you'll see that format is used for this conversion, and ?format shows a default trim = FALSE that says

修剪;如果 FALSE,逻辑值、数字值和复数值右对齐到一个共同的宽度:如果 TRUE 对齐的前导空格被抑制.

trim; if FALSE, logical, numeric and complex values are right-justified to a common width: if TRUE the leading blanks for justification are suppressed.

这就是你的问题!

pastepaste0 是矢量化的,所以没有理由一次 apply 它们一行.您可以直接将列粘贴在一起:

paste and paste0 are vectorized, so there's no reason to apply them one row at a time. You can just paste the columns together directly:

with(stop_latlon, paste0(lat, "%7", lon))

在更复杂的情况下,apply 确实是必要的,解决方案是处理您自己的矩阵转换,而不是依赖 apply 使用默认值来完成.如果您在将数据传递给 apply 之前制作所有列字符串,(或者如果您使用字符矩阵而不是数据框),则转换将很简单(或不必要).

In a more complicated case where apply really would be necessary, the solution would be to handle your own matrix conversion rather than relying on apply to do it with defaults. If you made all the columns strings before passing the data to apply, (or if you used a character matrix instead of a data frame), the conversion would be straightforward (or unnecessary).

这篇关于为什么 apply(x, 1, paste0(collapse="") 在正值之间留下空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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